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_typescript/tests/fixture/namespace/2/input.ts
TypeScript
class X1 {} namespace X1 { console.log(1); } function X2() {} namespace X2 { console.log(2); } enum X3 {} namespace X3 { console.log(3); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/fixture/namespace/2/output.js
JavaScript
class X1 { } (function(X1) { console.log(1); })(X1 || (X1 = {})); function X2() {} (function(X2) { console.log(2); })(X2 || (X2 = {})); var X3 = /*#__PURE__*/ function(X3) { return X3; }(X3 || {}); (function(X3) { console.log(3); })(X3 || (X3 = {}));
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/fixture/next-45561/1/input.tsx
TypeScript (TSX)
import path, { dirname } from "node:path"; export default function IndexPage(props: { abc: string }) { return ( <div> abc: {props.abc} <svg viewBox="0 -85 600 600"></svg> </div> ); } export function getServerSideProps() { return { props: { abc: dirname("/abc/def"), }, }; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/fixture/next-45561/1/output.js
JavaScript
import { dirname } from "node:path"; export default function IndexPage(props) { return React.createElement("div", null, "abc: ", props.abc, React.createElement("svg", { viewBox: "0 -85 600 600" })); } export function getServerSideProps() { return { props: { abc: dirname("/abc/def") } }; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/fixture/next-45561/2/input.tsx
TypeScript (TSX)
import path, { dirname } from "node:path"; export default function IndexPage(props: { abc: string }) { return ( <div> abc: {props.abc} <svg viewBox="0 -85 600 600"> <path fillRule="evenodd" d="M513 256.5C513 398.161 398.161 513 256.5 513C114.839 513 0 398.161 0 256.5C0 114.839 114.839 0 256.5 0C398.161 0 513 114.839 513 256.5ZM211.146 305.243L369.885 145L412 185.878L253.26 346.122L211.146 387L101 275.811L143.115 234.932L211.146 305.243Z" fill="#fff" /> </svg> </div> ); } export function getServerSideProps() { return { props: { abc: dirname("/abc/def"), }, }; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/fixture/next-45561/2/output.js
JavaScript
import { dirname } from "node:path"; export default function IndexPage(props) { return React.createElement("div", null, "abc: ", props.abc, React.createElement("svg", { viewBox: "0 -85 600 600" }, React.createElement("path", { fillRule: "evenodd", d: "M513 256.5C513 398.161 398.161 513 256.5 513C114.839 513 0 398.161 0 256.5C0 114.839 114.839 0 256.5 0C398.161 0 513 114.839 513 256.5ZM211.146 305.243L369.885 145L412 185.878L253.26 346.122L211.146 387L101 275.811L143.115 234.932L211.146 305.243Z", fill: "#fff" }))); } export function getServerSideProps() { return { props: { abc: dirname("/abc/def") } }; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/fixture/next/server/render/1/input.tsx
TypeScript (TSX)
import { IncomingMessage, ServerResponse } from "http"; import { ParsedUrlQuery } from "querystring"; import { Writable } from "stream"; import React from "react"; import * as ReactDOMServer from "react-dom/server"; import { StyleRegistry, createStyleRegistry } from "styled-jsx"; import { warn } from "../build/output/log"; import { UnwrapPromise } from "../lib/coalesced-function"; import { GSP_NO_RETURNED_VALUE, GSSP_COMPONENT_MEMBER_ERROR, GSSP_NO_RETURNED_VALUE, STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR, SERVER_PROPS_GET_INIT_PROPS_CONFLICT, SERVER_PROPS_SSG_CONFLICT, SSG_GET_INITIAL_PROPS_CONFLICT, UNSTABLE_REVALIDATE_RENAME_ERROR, } from "../lib/constants"; import { isSerializableProps } from "../lib/is-serializable-props"; import { GetServerSideProps, GetStaticProps, PreviewData } from "../types"; import { isInAmpMode } from "../shared/lib/amp"; import { AmpStateContext } from "../shared/lib/amp-context"; import { BODY_RENDER_TARGET, SERVER_PROPS_ID, STATIC_PROPS_ID, STATIC_STATUS_PAGES, } from "../shared/lib/constants"; import { defaultHead } from "../shared/lib/head"; import { HeadManagerContext } from "../shared/lib/head-manager-context"; import Loadable from "../shared/lib/loadable"; import { LoadableContext } from "../shared/lib/loadable-context"; import postProcess from "../shared/lib/post-process"; import { RouterContext } from "../shared/lib/router-context"; import { NextRouter } from "../shared/lib/router/router"; import { isDynamicRoute } from "../shared/lib/router/utils/is-dynamic"; import { AppType, ComponentsEnhancer, DocumentInitialProps, DocumentProps, DocumentContext, HtmlContext, HtmlProps, getDisplayName, isResSent, loadGetInitialProps, NextComponentType, RenderPage, RenderPageResult, } from "../shared/lib/utils"; import { tryGetPreviewData, NextApiRequestCookies, __ApiPreviewProps, } from "./api-utils"; import { denormalizePagePath } from "./denormalize-page-path"; import { FontManifest, getFontDefinitionFromManifest } from "./font-utils"; import { LoadComponentsReturnType, ManifestItem } from "./load-components"; import { normalizePagePath } from "./normalize-page-path"; import optimizeAmp from "./optimize-amp"; import { allowedStatusCodes, getRedirectStatus, Redirect, } from "../lib/load-custom-routes"; import { DomainLocale } from "./config"; import RenderResult, { NodeWritablePiper } from "./render-result"; import isError from "../lib/is-error"; function noRouter() { const message = 'No router instance found. you should only use "next/router" inside the client side of your app. https://nextjs.org/docs/messages/no-router-instance'; throw new Error(message); } class ServerRouter implements NextRouter { route: string; pathname: string; query: ParsedUrlQuery; asPath: string; basePath: string; events: any; isFallback: boolean; locale?: string; isReady: boolean; locales?: string[]; defaultLocale?: string; domainLocales?: DomainLocale[]; isPreview: boolean; isLocaleDomain: boolean; constructor( pathname: string, query: ParsedUrlQuery, as: string, { isFallback }: { isFallback: boolean }, isReady: boolean, basePath: string, locale?: string, locales?: string[], defaultLocale?: string, domainLocales?: DomainLocale[], isPreview?: boolean, isLocaleDomain?: boolean ) { this.route = pathname.replace(/\/$/, "") || "/"; this.pathname = pathname; this.query = query; this.asPath = as; this.isFallback = isFallback; this.basePath = basePath; this.locale = locale; this.locales = locales; this.defaultLocale = defaultLocale; this.isReady = isReady; this.domainLocales = domainLocales; this.isPreview = !!isPreview; this.isLocaleDomain = !!isLocaleDomain; } push(): any { noRouter(); } replace(): any { noRouter(); } reload() { noRouter(); } back() { noRouter(); } prefetch(): any { noRouter(); } beforePopState() { noRouter(); } } function enhanceComponents( options: ComponentsEnhancer, App: AppType, Component: NextComponentType ): { App: AppType; Component: NextComponentType; } { // For backwards compatibility if (typeof options === "function") { return { App, Component: options(Component), }; } return { App: options.enhanceApp ? options.enhanceApp(App) : App, Component: options.enhanceComponent ? options.enhanceComponent(Component) : Component, }; } export type RenderOptsPartial = { buildId: string; canonicalBase: string; runtimeConfig?: { [key: string]: any }; assetPrefix?: string; err?: Error | null; nextExport?: boolean; dev?: boolean; ampPath?: string; ErrorDebug?: React.ComponentType<{ error: Error }>; ampValidator?: (html: string, pathname: string) => Promise<void>; ampSkipValidation?: boolean; ampOptimizerConfig?: { [key: string]: any }; isDataReq?: boolean; params?: ParsedUrlQuery; previewProps: __ApiPreviewProps; basePath: string; unstable_runtimeJS?: false; unstable_JsPreload?: false; optimizeFonts: boolean; fontManifest?: FontManifest; optimizeImages: boolean; optimizeCss: any; devOnlyCacheBusterQueryString?: string; resolvedUrl?: string; resolvedAsPath?: string; distDir?: string; locale?: string; locales?: string[]; defaultLocale?: string; domainLocales?: DomainLocale[]; disableOptimizedLoading?: boolean; supportsDynamicHTML?: boolean; concurrentFeatures?: boolean; customServer?: boolean; }; export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial; const invalidKeysMsg = (methodName: string, invalidKeys: string[]) => { return ( `Additional keys were returned from \`${methodName}\`. Properties intended for your component must be nested under the \`props\` key, e.g.:` + `\n\n\treturn { props: { title: 'My Title', content: '...' } }` + `\n\nKeys that need to be moved: ${invalidKeys.join(", ")}.` + `\nRead more: https://nextjs.org/docs/messages/invalid-getstaticprops-value` ); }; function checkRedirectValues( redirect: Redirect, req: IncomingMessage, method: "getStaticProps" | "getServerSideProps" ) { const { destination, permanent, statusCode, basePath } = redirect; let errors: string[] = []; const hasStatusCode = typeof statusCode !== "undefined"; const hasPermanent = typeof permanent !== "undefined"; if (hasPermanent && hasStatusCode) { errors.push( `\`permanent\` and \`statusCode\` can not both be provided` ); } else if (hasPermanent && typeof permanent !== "boolean") { errors.push(`\`permanent\` must be \`true\` or \`false\``); } else if (hasStatusCode && !allowedStatusCodes.has(statusCode!)) { errors.push( `\`statusCode\` must undefined or one of ${[ ...allowedStatusCodes, ].join(", ")}` ); } const destinationType = typeof destination; if (destinationType !== "string") { errors.push( `\`destination\` should be string but received ${destinationType}` ); } const basePathType = typeof basePath; if (basePathType !== "undefined" && basePathType !== "boolean") { errors.push( `\`basePath\` should be undefined or a false, received ${basePathType}` ); } if (errors.length > 0) { throw new Error( `Invalid redirect object returned from ${method} for ${req.url}\n` + errors.join(" and ") + "\n" + `See more info here: https://nextjs.org/docs/messages/invalid-redirect-gssp` ); } } export async function renderToHTML( req: IncomingMessage, res: ServerResponse, pathname: string, query: ParsedUrlQuery, renderOpts: RenderOpts ): Promise<RenderResult | null> { // In dev we invalidate the cache by appending a timestamp to the resource URL. // This is a workaround to fix https://github.com/vercel/next.js/issues/5860 // TODO: remove this workaround when https://bugs.webkit.org/show_bug.cgi?id=187726 is fixed. renderOpts.devOnlyCacheBusterQueryString = renderOpts.dev ? renderOpts.devOnlyCacheBusterQueryString || `?ts=${Date.now()}` : ""; // don't modify original query object query = Object.assign({}, query); const { err, dev = false, ampPath = "", App, Document, pageConfig = {}, Component, buildManifest, fontManifest, reactLoadableManifest, ErrorDebug, getStaticProps, getStaticPaths, getServerSideProps, isDataReq, params, previewProps, basePath, devOnlyCacheBusterQueryString, supportsDynamicHTML, concurrentFeatures, } = renderOpts; const getFontDefinition = (url: string): string => { if (fontManifest) { return getFontDefinitionFromManifest(url, fontManifest); } return ""; }; const callMiddleware = async ( method: string, args: any[], props = false ) => { let results: any = props ? {} : []; if ((Document as any)[`${method}Middleware`]) { let middlewareFunc = await (Document as any)[`${method}Middleware`]; middlewareFunc = middlewareFunc.default || middlewareFunc; const curResults = await middlewareFunc(...args); if (props) { for (const result of curResults) { results = { ...results, ...result, }; } } else { results = curResults; } } return results; }; const headTags = (...args: any) => callMiddleware("headTags", args); const isFallback = !!query.__nextFallback; delete query.__nextFallback; delete query.__nextLocale; delete query.__nextDefaultLocale; const isSSG = !!getStaticProps; const isBuildTimeSSG = isSSG && renderOpts.nextExport; const defaultAppGetInitialProps = App.getInitialProps === (App as any).origGetInitialProps; const hasPageGetInitialProps = !!(Component as any).getInitialProps; const pageIsDynamic = isDynamicRoute(pathname); const isAutoExport = !hasPageGetInitialProps && defaultAppGetInitialProps && !isSSG && !getServerSideProps; for (const methodName of [ "getStaticProps", "getServerSideProps", "getStaticPaths", ]) { if ((Component as any)[methodName]) { throw new Error( `page ${pathname} ${methodName} ${GSSP_COMPONENT_MEMBER_ERROR}` ); } } if (hasPageGetInitialProps && isSSG) { throw new Error(SSG_GET_INITIAL_PROPS_CONFLICT + ` ${pathname}`); } if (hasPageGetInitialProps && getServerSideProps) { throw new Error(SERVER_PROPS_GET_INIT_PROPS_CONFLICT + ` ${pathname}`); } if (getServerSideProps && isSSG) { throw new Error(SERVER_PROPS_SSG_CONFLICT + ` ${pathname}`); } if (getStaticPaths && !pageIsDynamic) { throw new Error( `getStaticPaths is only allowed for dynamic SSG pages and was found on '${pathname}'.` + `\nRead more: https://nextjs.org/docs/messages/non-dynamic-getstaticpaths-usage` ); } if (!!getStaticPaths && !isSSG) { throw new Error( `getStaticPaths was added without a getStaticProps in ${pathname}. Without getStaticProps, getStaticPaths does nothing` ); } if (isSSG && pageIsDynamic && !getStaticPaths) { throw new Error( `getStaticPaths is required for dynamic SSG pages and is missing for '${pathname}'.` + `\nRead more: https://nextjs.org/docs/messages/invalid-getstaticpaths-value` ); } let asPath: string = renderOpts.resolvedAsPath || (req.url as string); if (dev) { const { isValidElementType } = require("react-is"); if (!isValidElementType(Component)) { throw new Error( `The default export is not a React Component in page: "${pathname}"` ); } if (!isValidElementType(App)) { throw new Error( `The default export is not a React Component in page: "/_app"` ); } if (!isValidElementType(Document)) { throw new Error( `The default export is not a React Component in page: "/_document"` ); } if (isAutoExport || isFallback) { // remove query values except ones that will be set during export query = { ...(query.amp ? { amp: query.amp, } : {}), }; asPath = `${pathname}${ // ensure trailing slash is present for non-dynamic auto-export pages req.url!.endsWith("/") && pathname !== "/" && !pageIsDynamic ? "/" : "" }`; req.url = pathname; } if ( pathname === "/404" && (hasPageGetInitialProps || getServerSideProps) ) { throw new Error( `\`pages/404\` ${STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR}` ); } if ( STATIC_STATUS_PAGES.includes(pathname) && (hasPageGetInitialProps || getServerSideProps) ) { throw new Error( `\`pages${pathname}\` ${STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR}` ); } } await Loadable.preloadAll(); // Make sure all dynamic imports are loaded let isPreview; let previewData: PreviewData; if ((isSSG || getServerSideProps) && !isFallback) { // Reads of this are cached on the `req` object, so this should resolve // instantly. There's no need to pass this data down from a previous // invoke, where we'd have to consider server & serverless. previewData = tryGetPreviewData(req, res, previewProps); isPreview = previewData !== false; } // url will always be set const routerIsReady = !!( getServerSideProps || hasPageGetInitialProps || (!defaultAppGetInitialProps && !isSSG) ); const router = new ServerRouter( pathname, query, asPath, { isFallback: isFallback, }, routerIsReady, basePath, renderOpts.locale, renderOpts.locales, renderOpts.defaultLocale, renderOpts.domainLocales, isPreview, (req as any).__nextIsLocaleDomain ); const jsxStyleRegistry = createStyleRegistry(); const ctx = { err, req: isAutoExport ? undefined : req, res: isAutoExport ? undefined : res, pathname, query, asPath, locale: renderOpts.locale, locales: renderOpts.locales, defaultLocale: renderOpts.defaultLocale, AppTree: (props: any) => { return ( <AppContainer> <App {...props} Component={Component} router={router} /> </AppContainer> ); }, defaultGetInitialProps: async ( docCtx: DocumentContext ): Promise<DocumentInitialProps> => { const enhanceApp = (AppComp: any) => { return (props: any) => <AppComp {...props} />; }; const { html, head } = await docCtx.renderPage({ enhanceApp }); const styles = jsxStyleRegistry.styles(); return { html, head, styles }; }, }; let props: any; const ampState = { ampFirst: pageConfig.amp === true, hasQuery: Boolean(query.amp), hybrid: pageConfig.amp === "hybrid", }; const inAmpMode = isInAmpMode(ampState); const reactLoadableModules: string[] = []; let head: JSX.Element[] = defaultHead(inAmpMode); let scriptLoader: any = {}; const nextExport = !isSSG && (renderOpts.nextExport || (dev && (isAutoExport || isFallback))); const AppContainer = ({ children }: { children: JSX.Element }) => ( <RouterContext.Provider value={router}> <AmpStateContext.Provider value={ampState}> <HeadManagerContext.Provider value={{ updateHead: (state) => { head = state; }, updateScripts: (scripts) => { scriptLoader = scripts; }, scripts: {}, mountedInstances: new Set(), }} > <LoadableContext.Provider value={(moduleName) => reactLoadableModules.push(moduleName) } > <StyleRegistry registry={jsxStyleRegistry}> {children} </StyleRegistry> </LoadableContext.Provider> </HeadManagerContext.Provider> </AmpStateContext.Provider> </RouterContext.Provider> ); props = await loadGetInitialProps(App, { AppTree: ctx.AppTree, Component, router, ctx, }); if ((isSSG || getServerSideProps) && isPreview) { props.__N_PREVIEW = true; } if (isSSG) { props[STATIC_PROPS_ID] = true; } if (isSSG && !isFallback) { let data: UnwrapPromise<ReturnType<GetStaticProps>>; try { data = await getStaticProps!({ ...(pageIsDynamic ? { params: query as ParsedUrlQuery } : undefined), ...(isPreview ? { preview: true, previewData: previewData } : undefined), locales: renderOpts.locales, locale: renderOpts.locale, defaultLocale: renderOpts.defaultLocale, }); } catch (staticPropsError: any) { // remove not found error code to prevent triggering legacy // 404 rendering if (staticPropsError && staticPropsError.code === "ENOENT") { delete staticPropsError.code; } throw staticPropsError; } if (data == null) { throw new Error(GSP_NO_RETURNED_VALUE); } const invalidKeys = Object.keys(data).filter( (key) => key !== "revalidate" && key !== "props" && key !== "redirect" && key !== "notFound" ); if (invalidKeys.includes("unstable_revalidate")) { throw new Error(UNSTABLE_REVALIDATE_RENAME_ERROR); } if (invalidKeys.length) { throw new Error(invalidKeysMsg("getStaticProps", invalidKeys)); } if (process.env.NODE_ENV !== "production") { if ( typeof (data as any).notFound !== "undefined" && typeof (data as any).redirect !== "undefined" ) { throw new Error( `\`redirect\` and \`notFound\` can not both be returned from ${ isSSG ? "getStaticProps" : "getServerSideProps" } at the same time. Page: ${pathname}\nSee more info here: https://nextjs.org/docs/messages/gssp-mixed-not-found-redirect` ); } } if ("notFound" in data && data.notFound) { if (pathname === "/404") { throw new Error( `The /404 page can not return notFound in "getStaticProps", please remove it to continue!` ); } (renderOpts as any).isNotFound = true; } if ( "redirect" in data && data.redirect && typeof data.redirect === "object" ) { checkRedirectValues( data.redirect as Redirect, req, "getStaticProps" ); if (isBuildTimeSSG) { throw new Error( `\`redirect\` can not be returned from getStaticProps during prerendering (${req.url})\n` + `See more info here: https://nextjs.org/docs/messages/gsp-redirect-during-prerender` ); } (data as any).props = { __N_REDIRECT: data.redirect.destination, __N_REDIRECT_STATUS: getRedirectStatus(data.redirect), }; if (typeof data.redirect.basePath !== "undefined") { (data as any).props.__N_REDIRECT_BASE_PATH = data.redirect.basePath; } (renderOpts as any).isRedirect = true; } if ( (dev || isBuildTimeSSG) && !(renderOpts as any).isNotFound && !isSerializableProps( pathname, "getStaticProps", (data as any).props ) ) { // this fn should throw an error instead of ever returning `false` throw new Error( "invariant: getStaticProps did not return valid props. Please report this." ); } if ("revalidate" in data) { if (typeof data.revalidate === "number") { if (!Number.isInteger(data.revalidate)) { throw new Error( `A page's revalidate option must be seconds expressed as a natural number for ${req.url}. Mixed numbers, such as '${data.revalidate}', cannot be used.` + `\nTry changing the value to '${Math.ceil( data.revalidate )}' or using \`Math.ceil()\` if you're computing the value.` ); } else if (data.revalidate <= 0) { throw new Error( `A page's revalidate option can not be less than or equal to zero for ${req.url}. A revalidate option of zero means to revalidate after _every_ request, and implies stale data cannot be tolerated.` + `\n\nTo never revalidate, you can set revalidate to \`false\` (only ran once at build-time).` + `\nTo revalidate as soon as possible, you can set the value to \`1\`.` ); } else if (data.revalidate > 31536000) { // if it's greater than a year for some reason error console.warn( `Warning: A page's revalidate option was set to more than a year for ${req.url}. This may have been done in error.` + `\nTo only run getStaticProps at build-time and not revalidate at runtime, you can set \`revalidate\` to \`false\`!` ); } } else if (data.revalidate === true) { // When enabled, revalidate after 1 second. This value is optimal for // the most up-to-date page possible, but without a 1-to-1 // request-refresh ratio. data.revalidate = 1; } else if ( data.revalidate === false || typeof data.revalidate === "undefined" ) { // By default, we never revalidate. data.revalidate = false; } else { throw new Error( `A page's revalidate option must be seconds expressed as a natural number. Mixed numbers and strings cannot be used. Received '${JSON.stringify( data.revalidate )}' for ${req.url}` ); } } else { // By default, we never revalidate. (data as any).revalidate = false; } props.pageProps = Object.assign( {}, props.pageProps, "props" in data ? data.props : undefined ); // pass up revalidate and props for export // TODO: change this to a different passing mechanism (renderOpts as any).revalidate = "revalidate" in data ? data.revalidate : undefined; (renderOpts as any).pageData = props; // this must come after revalidate is added to renderOpts if ((renderOpts as any).isNotFound) { return null; } } if (getServerSideProps) { props[SERVER_PROPS_ID] = true; } if (getServerSideProps && !isFallback) { let data: UnwrapPromise<ReturnType<GetServerSideProps>>; let canAccessRes = true; let resOrProxy = res; if (process.env.NODE_ENV !== "production") { resOrProxy = new Proxy<ServerResponse>(res, { get: function (obj, prop, receiver) { if (!canAccessRes) { throw new Error( `You should not access 'res' after getServerSideProps resolves.` + `\nRead more: https://nextjs.org/docs/messages/gssp-no-mutating-res` ); } return Reflect.get(obj, prop, receiver); }, }); } try { data = await getServerSideProps({ req: req as IncomingMessage & { cookies: NextApiRequestCookies; }, res: resOrProxy, query, resolvedUrl: renderOpts.resolvedUrl as string, ...(pageIsDynamic ? { params: params as ParsedUrlQuery } : undefined), ...(previewData !== false ? { preview: true, previewData: previewData } : undefined), locales: renderOpts.locales, locale: renderOpts.locale, defaultLocale: renderOpts.defaultLocale, }); canAccessRes = false; } catch (serverSidePropsError: any) { // remove not found error code to prevent triggering legacy // 404 rendering if ( isError(serverSidePropsError) && serverSidePropsError.code === "ENOENT" ) { delete serverSidePropsError.code; } throw serverSidePropsError; } if (data == null) { throw new Error(GSSP_NO_RETURNED_VALUE); } const invalidKeys = Object.keys(data).filter( (key) => key !== "props" && key !== "redirect" && key !== "notFound" ); if ((data as any).unstable_notFound) { throw new Error( `unstable_notFound has been renamed to notFound, please update the field to continue. Page: ${pathname}` ); } if ((data as any).unstable_redirect) { throw new Error( `unstable_redirect has been renamed to redirect, please update the field to continue. Page: ${pathname}` ); } if (invalidKeys.length) { throw new Error(invalidKeysMsg("getServerSideProps", invalidKeys)); } if ("notFound" in data && data.notFound) { if (pathname === "/404") { throw new Error( `The /404 page can not return notFound in "getStaticProps", please remove it to continue!` ); } (renderOpts as any).isNotFound = true; return null; } if ("redirect" in data && typeof data.redirect === "object") { checkRedirectValues( data.redirect as Redirect, req, "getServerSideProps" ); (data as any).props = { __N_REDIRECT: data.redirect.destination, __N_REDIRECT_STATUS: getRedirectStatus(data.redirect), }; if (typeof data.redirect.basePath !== "undefined") { (data as any).props.__N_REDIRECT_BASE_PATH = data.redirect.basePath; } (renderOpts as any).isRedirect = true; } if ((data as any).props instanceof Promise) { (data as any).props = await (data as any).props; } if ( (dev || isBuildTimeSSG) && !isSerializableProps( pathname, "getServerSideProps", (data as any).props ) ) { // this fn should throw an error instead of ever returning `false` throw new Error( "invariant: getServerSideProps did not return valid props. Please report this." ); } props.pageProps = Object.assign( {}, props.pageProps, (data as any).props ); (renderOpts as any).pageData = props; } if ( !isSSG && // we only show this warning for legacy pages !getServerSideProps && process.env.NODE_ENV !== "production" && Object.keys(props?.pageProps || {}).includes("url") ) { console.warn( `The prop \`url\` is a reserved prop in Next.js for legacy reasons and will be overridden on page ${pathname}\n` + `See more info here: https://nextjs.org/docs/messages/reserved-page-prop` ); } // Avoid rendering page un-necessarily for getServerSideProps data request // and getServerSideProps/getStaticProps redirects if ((isDataReq && !isSSG) || (renderOpts as any).isRedirect) { return RenderResult.fromStatic(JSON.stringify(props)); } // We don't call getStaticProps or getServerSideProps while generating // the fallback so make sure to set pageProps to an empty object if (isFallback) { props.pageProps = {}; } // the response might be finished on the getInitialProps call if (isResSent(res) && !isSSG) return null; // we preload the buildManifest for auto-export dynamic pages // to speed up hydrating query values let filteredBuildManifest = buildManifest; if (isAutoExport && pageIsDynamic) { const page = denormalizePagePath(normalizePagePath(pathname)); // This code would be much cleaner using `immer` and directly pushing into // the result from `getPageFiles`, we could maybe consider that in the // future. if (page in filteredBuildManifest.pages) { filteredBuildManifest = { ...filteredBuildManifest, pages: { ...filteredBuildManifest.pages, [page]: [ ...filteredBuildManifest.pages[page], ...filteredBuildManifest.lowPriorityFiles.filter((f) => f.includes("_buildManifest") ), ], }, lowPriorityFiles: filteredBuildManifest.lowPriorityFiles.filter( (f) => !f.includes("_buildManifest") ), }; } } /** * Rules of Static & Dynamic HTML: * * 1.) We must generate static HTML unless the caller explicitly opts * in to dynamic HTML support. * * 2.) If dynamic HTML support is requested, we must honor that request * or throw an error. It is the sole responsibility of the caller to * ensure they aren't e.g. requesting dynamic HTML for an AMP page. * * These rules help ensure that other existing features like request caching, * coalescing, and ISR continue working as intended. */ const generateStaticHTML = supportsDynamicHTML !== true; const renderDocument = async () => { if (Document.getInitialProps) { const renderPage: RenderPage = ( options: ComponentsEnhancer = {} ): RenderPageResult | Promise<RenderPageResult> => { if (ctx.err && ErrorDebug) { const html = ReactDOMServer.renderToString( <ErrorDebug error={ctx.err} /> ); return { html, head }; } if (dev && (props.router || props.Component)) { throw new Error( `'router' and 'Component' can not be returned in getInitialProps from _app.js https://nextjs.org/docs/messages/cant-override-next-props` ); } const { App: EnhancedApp, Component: EnhancedComponent } = enhanceComponents(options, App, Component); const html = ReactDOMServer.renderToString( <AppContainer> <EnhancedApp Component={EnhancedComponent} router={router} {...props} /> </AppContainer> ); return { html, head }; }; const documentCtx = { ...ctx, renderPage }; const docProps: DocumentInitialProps = await loadGetInitialProps( Document, documentCtx ); // the response might be finished on the getInitialProps call if (isResSent(res) && !isSSG) return null; if (!docProps || typeof docProps.html !== "string") { const message = `"${getDisplayName( Document )}.getInitialProps()" should resolve to an object with a "html" prop set with a valid html string`; throw new Error(message); } return { bodyResult: piperFromArray([docProps.html]), documentElement: (htmlProps: HtmlProps) => ( <Document {...htmlProps} {...docProps} /> ), head: docProps.head, headTags: await headTags(documentCtx), styles: docProps.styles, }; } else { const content = ctx.err && ErrorDebug ? ( <ErrorDebug error={ctx.err} /> ) : ( <AppContainer> <App {...props} Component={Component} router={router} /> </AppContainer> ); const bodyResult = concurrentFeatures ? await renderToStream(content, generateStaticHTML) : piperFromArray([ReactDOMServer.renderToString(content)]); return { bodyResult, documentElement: () => (Document as any)(), head, headTags: [], styles: jsxStyleRegistry.styles(), }; } }; const documentResult = await renderDocument(); if (!documentResult) { return null; } const dynamicImportsIds = new Set<string | number>(); const dynamicImports = new Set<string>(); for (const mod of reactLoadableModules) { const manifestItem: ManifestItem = reactLoadableManifest[mod]; if (manifestItem) { dynamicImportsIds.add(manifestItem.id); manifestItem.files.forEach((item) => { dynamicImports.add(item); }); } } const hybridAmp = ampState.hybrid; const docComponentsRendered: DocumentProps["docComponentsRendered"] = {}; const { assetPrefix, buildId, customServer, defaultLocale, disableOptimizedLoading, domainLocales, locale, locales, runtimeConfig, } = renderOpts; const htmlProps: any = { __NEXT_DATA__: { props, // The result of getInitialProps page: pathname, // The rendered page query, // querystring parsed / passed by the user buildId, // buildId is used to facilitate caching of page bundles, we send it to the client so that pageloader knows where to load bundles assetPrefix: assetPrefix === "" ? undefined : assetPrefix, // send assetPrefix to the client side when configured, otherwise don't sent in the resulting HTML runtimeConfig, // runtimeConfig if provided, otherwise don't sent in the resulting HTML nextExport: nextExport === true ? true : undefined, // If this is a page exported by `next export` autoExport: isAutoExport === true ? true : undefined, // If this is an auto exported page isFallback, dynamicIds: dynamicImportsIds.size === 0 ? undefined : Array.from(dynamicImportsIds), err: renderOpts.err ? serializeError(dev, renderOpts.err) : undefined, // Error if one happened, otherwise don't sent in the resulting HTML gsp: !!getStaticProps ? true : undefined, // whether the page is getStaticProps gssp: !!getServerSideProps ? true : undefined, // whether the page is getServerSideProps customServer, // whether the user is using a custom server gip: hasPageGetInitialProps ? true : undefined, // whether the page has getInitialProps appGip: !defaultAppGetInitialProps ? true : undefined, // whether the _app has getInitialProps locale, locales, defaultLocale, domainLocales, isPreview: isPreview === true ? true : undefined, }, buildManifest: filteredBuildManifest, docComponentsRendered, dangerousAsPath: router.asPath, canonicalBase: !renderOpts.ampPath && (req as any).__nextStrippedLocale ? `${renderOpts.canonicalBase || ""}/${renderOpts.locale}` : renderOpts.canonicalBase, ampPath, inAmpMode, isDevelopment: !!dev, hybridAmp, dynamicImports: Array.from(dynamicImports), assetPrefix, // Only enabled in production as development mode has features relying on HMR (style injection for example) unstable_runtimeJS: process.env.NODE_ENV === "production" ? pageConfig.unstable_runtimeJS : undefined, unstable_JsPreload: pageConfig.unstable_JsPreload, devOnlyCacheBusterQueryString, scriptLoader, locale, disableOptimizedLoading, head: documentResult.head, headTags: documentResult.headTags, styles: documentResult.styles, useMaybeDeferContent, }; const documentHTML = ReactDOMServer.renderToStaticMarkup( <AmpStateContext.Provider value={ampState}> <HtmlContext.Provider value={htmlProps}> {documentResult.documentElement(htmlProps)} </HtmlContext.Provider> </AmpStateContext.Provider> ); if (process.env.NODE_ENV !== "production") { const nonRenderedComponents = []; const expectedDocComponents = ["Main", "Head", "NextScript", "Html"]; for (const comp of expectedDocComponents) { if (!(docComponentsRendered as any)[comp]) { nonRenderedComponents.push(comp); } } const plural = nonRenderedComponents.length !== 1 ? "s" : ""; if (nonRenderedComponents.length) { const missingComponentList = nonRenderedComponents .map((e) => `<${e} />`) .join(", "); warn( `Your custom Document (pages/_document) did not render all the required subcomponent${plural}.\n` + `Missing component${plural}: ${missingComponentList}\n` + "Read how to fix here: https://nextjs.org/docs/messages/missing-document-component" ); } } const renderTargetIdx = documentHTML.indexOf(BODY_RENDER_TARGET); const prefix: Array<string> = []; prefix.push("<!DOCTYPE html>"); prefix.push(documentHTML.substring(0, renderTargetIdx)); if (inAmpMode) { prefix.push("<!-- __NEXT_DATA__ -->"); } let pipers: Array<NodeWritablePiper> = [ piperFromArray(prefix), documentResult.bodyResult, piperFromArray([ documentHTML.substring(renderTargetIdx + BODY_RENDER_TARGET.length), ]), ]; const postProcessors: Array<((html: string) => Promise<string>) | null> = ( generateStaticHTML ? [ inAmpMode ? async (html: string) => { html = await optimizeAmp( html, renderOpts.ampOptimizerConfig ); if ( !renderOpts.ampSkipValidation && renderOpts.ampValidator ) { await renderOpts.ampValidator(html, pathname); } return html; } : null, process.env.__NEXT_OPTIMIZE_FONTS || process.env.__NEXT_OPTIMIZE_IMAGES ? async (html: string) => { return await postProcess( html, { getFontDefinition }, { optimizeFonts: renderOpts.optimizeFonts, optimizeImages: renderOpts.optimizeImages, } ); } : null, renderOpts.optimizeCss ? async (html: string) => { // eslint-disable-next-line import/no-extraneous-dependencies const Critters = require("critters"); const cssOptimizer = new Critters({ ssrMode: true, reduceInlineStyles: false, path: renderOpts.distDir, publicPath: `${renderOpts.assetPrefix}/_next/`, preload: "media", fonts: false, ...renderOpts.optimizeCss, }); return await cssOptimizer.process(html); } : null, inAmpMode || hybridAmp ? async (html: string) => { return html.replace(/&amp;amp=1/g, "&amp=1"); } : null, ] : [] ).filter(Boolean); if (generateStaticHTML || postProcessors.length > 0) { let html = await piperToString(chainPipers(pipers)); for (const postProcessor of postProcessors) { if (postProcessor) { html = await postProcessor(html); } } return new RenderResult(html); } return new RenderResult(chainPipers(pipers)); } function errorToJSON(err: Error): Error { const { name, message, stack } = err; return { name, message, stack }; } function serializeError( dev: boolean | undefined, err: Error ): Error & { statusCode?: number } { if (dev) { return errorToJSON(err); } return { name: "Internal Server Error.", message: "500 - Internal Server Error.", statusCode: 500, }; } function renderToStream( element: React.ReactElement, generateStaticHTML: boolean ): Promise<NodeWritablePiper> { return new Promise((resolve, reject) => { let underlyingStream: { resolve: (error?: Error) => void; writable: Writable; queuedCallbacks: Array<() => void>; } | null = null; const stream = new Writable({ // Use the buffer from the underlying stream highWaterMark: 0, write(chunk, encoding, callback) { if (!underlyingStream) { throw new Error( "invariant: write called without an underlying stream. This is a bug in Next.js" ); } if (!underlyingStream.writable.write(chunk, encoding)) { underlyingStream.queuedCallbacks.push(() => callback()); } else { callback(); } }, }); stream.once("finish", () => { if (!underlyingStream) { throw new Error( "invariant: finish called without an underlying stream. This is a bug in Next.js" ); } underlyingStream.resolve(); }); stream.once("error", (err) => { if (!underlyingStream) { throw new Error( "invariant: error called without an underlying stream. This is a bug in Next.js" ); } underlyingStream.resolve(err); }); // React uses `flush` to prevent stream middleware like gzip from buffering to the // point of harming streaming performance, so we make sure to expose it and forward it. // See: https://github.com/reactwg/react-18/discussions/91 Object.defineProperty(stream, "flush", { value: () => { if (!underlyingStream) { throw new Error( "invariant: flush called without an underlying stream. This is a bug in Next.js" ); } if ( typeof (underlyingStream.writable as any).flush === "function" ) { (underlyingStream.writable as any).flush(); } }, enumerable: true, }); let resolved = false; const doResolve = () => { if (!resolved) { resolved = true; resolve((res, next) => { const drainHandler = () => { const prevCallbacks = underlyingStream!.queuedCallbacks; underlyingStream!.queuedCallbacks = []; prevCallbacks.forEach((callback) => callback()); }; res.on("drain", drainHandler); underlyingStream = { resolve: (err) => { underlyingStream = null; res.removeListener("drain", drainHandler); next(err); }, writable: res, queuedCallbacks: [], }; startWriting(); }); } }; const { abort, startWriting } = ( ReactDOMServer as any ).pipeToNodeWritable(element, stream, { onError(error: Error) { if (!resolved) { resolved = true; reject(error); } abort(); }, onCompleteShell() { if (!generateStaticHTML) { doResolve(); } }, onCompleteAll() { doResolve(); }, }); }); } function chainPipers(pipers: NodeWritablePiper[]): NodeWritablePiper { return pipers.reduceRight( (lhs, rhs) => (res, next) => { rhs(res, (err) => (err ? next(err) : lhs(res, next))); }, (res, next) => { res.end(); next(); } ); } function piperFromArray(chunks: string[]): NodeWritablePiper { return (res, next) => { if (typeof (res as any).cork === "function") { res.cork(); } chunks.forEach((chunk) => res.write(chunk)); if (typeof (res as any).uncork === "function") { res.uncork(); } next(); }; } function piperToString(input: NodeWritablePiper): Promise<string> { return new Promise((resolve, reject) => { const bufferedChunks: Buffer[] = []; const stream = new Writable({ writev(chunks, callback) { chunks.forEach((chunk) => bufferedChunks.push(chunk.chunk)); callback(); }, }); input(stream, (err) => { if (err) { reject(err); } else { resolve(Buffer.concat(bufferedChunks).toString()); } }); }); } export function useMaybeDeferContent( _name: string, contentFn: () => JSX.Element ): [boolean, JSX.Element] { return [false, contentFn()]; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/fixture/next/server/render/1/output.js
JavaScript
import { Writable } from "stream"; import * as ReactDOMServer from "react-dom/server"; import { StyleRegistry, createStyleRegistry } from "styled-jsx"; import { warn } from "../build/output/log"; import { GSP_NO_RETURNED_VALUE, GSSP_COMPONENT_MEMBER_ERROR, GSSP_NO_RETURNED_VALUE, STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR, SERVER_PROPS_GET_INIT_PROPS_CONFLICT, SERVER_PROPS_SSG_CONFLICT, SSG_GET_INITIAL_PROPS_CONFLICT, UNSTABLE_REVALIDATE_RENAME_ERROR } from "../lib/constants"; import { isSerializableProps } from "../lib/is-serializable-props"; import { isInAmpMode } from "../shared/lib/amp"; import { AmpStateContext } from "../shared/lib/amp-context"; import { BODY_RENDER_TARGET, SERVER_PROPS_ID, STATIC_PROPS_ID, STATIC_STATUS_PAGES } from "../shared/lib/constants"; import { defaultHead } from "../shared/lib/head"; import { HeadManagerContext } from "../shared/lib/head-manager-context"; import Loadable from "../shared/lib/loadable"; import { LoadableContext } from "../shared/lib/loadable-context"; import postProcess from "../shared/lib/post-process"; import { RouterContext } from "../shared/lib/router-context"; import { isDynamicRoute } from "../shared/lib/router/utils/is-dynamic"; import { HtmlContext, getDisplayName, isResSent, loadGetInitialProps } from "../shared/lib/utils"; import { tryGetPreviewData } from "./api-utils"; import { denormalizePagePath } from "./denormalize-page-path"; import { getFontDefinitionFromManifest } from "./font-utils"; import { normalizePagePath } from "./normalize-page-path"; import optimizeAmp from "./optimize-amp"; import { allowedStatusCodes, getRedirectStatus } from "../lib/load-custom-routes"; import RenderResult from "./render-result"; import isError from "../lib/is-error"; function noRouter() { const message = 'No router instance found. you should only use "next/router" inside the client side of your app. https://nextjs.org/docs/messages/no-router-instance'; throw new Error(message); } class ServerRouter { push() { noRouter(); } replace() { noRouter(); } reload() { noRouter(); } back() { noRouter(); } prefetch() { noRouter(); } beforePopState() { noRouter(); } constructor(pathname, query, as, { isFallback }, isReady, basePath, locale, locales, defaultLocale, domainLocales, isPreview, isLocaleDomain){ this.route = pathname.replace(/\/$/, "") || "/"; this.pathname = pathname; this.query = query; this.asPath = as; this.isFallback = isFallback; this.basePath = basePath; this.locale = locale; this.locales = locales; this.defaultLocale = defaultLocale; this.isReady = isReady; this.domainLocales = domainLocales; this.isPreview = !!isPreview; this.isLocaleDomain = !!isLocaleDomain; } } function enhanceComponents(options, App, Component) { // For backwards compatibility if (typeof options === "function") { return { App, Component: options(Component) }; } return { App: options.enhanceApp ? options.enhanceApp(App) : App, Component: options.enhanceComponent ? options.enhanceComponent(Component) : Component }; } const invalidKeysMsg = (methodName, invalidKeys)=>{ return `Additional keys were returned from \`${methodName}\`. Properties intended for your component must be nested under the \`props\` key, e.g.:` + `\n\n\treturn { props: { title: 'My Title', content: '...' } }` + `\n\nKeys that need to be moved: ${invalidKeys.join(", ")}.` + `\nRead more: https://nextjs.org/docs/messages/invalid-getstaticprops-value`; }; function checkRedirectValues(redirect, req, method) { const { destination, permanent, statusCode, basePath } = redirect; let errors = []; const hasStatusCode = typeof statusCode !== "undefined"; const hasPermanent = typeof permanent !== "undefined"; if (hasPermanent && hasStatusCode) { errors.push(`\`permanent\` and \`statusCode\` can not both be provided`); } else if (hasPermanent && typeof permanent !== "boolean") { errors.push(`\`permanent\` must be \`true\` or \`false\``); } else if (hasStatusCode && !allowedStatusCodes.has(statusCode)) { errors.push(`\`statusCode\` must undefined or one of ${[ ...allowedStatusCodes ].join(", ")}`); } const destinationType = typeof destination; if (destinationType !== "string") { errors.push(`\`destination\` should be string but received ${destinationType}`); } const basePathType = typeof basePath; if (basePathType !== "undefined" && basePathType !== "boolean") { errors.push(`\`basePath\` should be undefined or a false, received ${basePathType}`); } if (errors.length > 0) { throw new Error(`Invalid redirect object returned from ${method} for ${req.url}\n` + errors.join(" and ") + "\n" + `See more info here: https://nextjs.org/docs/messages/invalid-redirect-gssp`); } } export async function renderToHTML(req, res, pathname, query, renderOpts) { // In dev we invalidate the cache by appending a timestamp to the resource URL. // This is a workaround to fix https://github.com/vercel/next.js/issues/5860 // TODO: remove this workaround when https://bugs.webkit.org/show_bug.cgi?id=187726 is fixed. renderOpts.devOnlyCacheBusterQueryString = renderOpts.dev ? renderOpts.devOnlyCacheBusterQueryString || `?ts=${Date.now()}` : ""; // don't modify original query object query = Object.assign({}, query); const { err, dev = false, ampPath = "", App, Document, pageConfig = {}, Component, buildManifest, fontManifest, reactLoadableManifest, ErrorDebug, getStaticProps, getStaticPaths, getServerSideProps, isDataReq, params, previewProps, basePath, devOnlyCacheBusterQueryString, supportsDynamicHTML, concurrentFeatures } = renderOpts; const getFontDefinition = (url)=>{ if (fontManifest) { return getFontDefinitionFromManifest(url, fontManifest); } return ""; }; const callMiddleware = async (method, args, props = false)=>{ let results = props ? {} : []; if (Document[`${method}Middleware`]) { let middlewareFunc = await Document[`${method}Middleware`]; middlewareFunc = middlewareFunc.default || middlewareFunc; const curResults = await middlewareFunc(...args); if (props) { for (const result of curResults){ results = { ...results, ...result }; } } else { results = curResults; } } return results; }; const headTags = (...args)=>callMiddleware("headTags", args); const isFallback = !!query.__nextFallback; delete query.__nextFallback; delete query.__nextLocale; delete query.__nextDefaultLocale; const isSSG = !!getStaticProps; const isBuildTimeSSG = isSSG && renderOpts.nextExport; const defaultAppGetInitialProps = App.getInitialProps === App.origGetInitialProps; const hasPageGetInitialProps = !!Component.getInitialProps; const pageIsDynamic = isDynamicRoute(pathname); const isAutoExport = !hasPageGetInitialProps && defaultAppGetInitialProps && !isSSG && !getServerSideProps; for (const methodName of [ "getStaticProps", "getServerSideProps", "getStaticPaths" ]){ if (Component[methodName]) { throw new Error(`page ${pathname} ${methodName} ${GSSP_COMPONENT_MEMBER_ERROR}`); } } if (hasPageGetInitialProps && isSSG) { throw new Error(SSG_GET_INITIAL_PROPS_CONFLICT + ` ${pathname}`); } if (hasPageGetInitialProps && getServerSideProps) { throw new Error(SERVER_PROPS_GET_INIT_PROPS_CONFLICT + ` ${pathname}`); } if (getServerSideProps && isSSG) { throw new Error(SERVER_PROPS_SSG_CONFLICT + ` ${pathname}`); } if (getStaticPaths && !pageIsDynamic) { throw new Error(`getStaticPaths is only allowed for dynamic SSG pages and was found on '${pathname}'.` + `\nRead more: https://nextjs.org/docs/messages/non-dynamic-getstaticpaths-usage`); } if (!!getStaticPaths && !isSSG) { throw new Error(`getStaticPaths was added without a getStaticProps in ${pathname}. Without getStaticProps, getStaticPaths does nothing`); } if (isSSG && pageIsDynamic && !getStaticPaths) { throw new Error(`getStaticPaths is required for dynamic SSG pages and is missing for '${pathname}'.` + `\nRead more: https://nextjs.org/docs/messages/invalid-getstaticpaths-value`); } let asPath = renderOpts.resolvedAsPath || req.url; if (dev) { const { isValidElementType } = require("react-is"); if (!isValidElementType(Component)) { throw new Error(`The default export is not a React Component in page: "${pathname}"`); } if (!isValidElementType(App)) { throw new Error(`The default export is not a React Component in page: "/_app"`); } if (!isValidElementType(Document)) { throw new Error(`The default export is not a React Component in page: "/_document"`); } if (isAutoExport || isFallback) { // remove query values except ones that will be set during export query = { ...query.amp ? { amp: query.amp } : {} }; asPath = `${pathname}${// ensure trailing slash is present for non-dynamic auto-export pages req.url.endsWith("/") && pathname !== "/" && !pageIsDynamic ? "/" : ""}`; req.url = pathname; } if (pathname === "/404" && (hasPageGetInitialProps || getServerSideProps)) { throw new Error(`\`pages/404\` ${STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR}`); } if (STATIC_STATUS_PAGES.includes(pathname) && (hasPageGetInitialProps || getServerSideProps)) { throw new Error(`\`pages${pathname}\` ${STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR}`); } } await Loadable.preloadAll(); // Make sure all dynamic imports are loaded let isPreview; let previewData; if ((isSSG || getServerSideProps) && !isFallback) { // Reads of this are cached on the `req` object, so this should resolve // instantly. There's no need to pass this data down from a previous // invoke, where we'd have to consider server & serverless. previewData = tryGetPreviewData(req, res, previewProps); isPreview = previewData !== false; } // url will always be set const routerIsReady = !!(getServerSideProps || hasPageGetInitialProps || !defaultAppGetInitialProps && !isSSG); const router = new ServerRouter(pathname, query, asPath, { isFallback: isFallback }, routerIsReady, basePath, renderOpts.locale, renderOpts.locales, renderOpts.defaultLocale, renderOpts.domainLocales, isPreview, req.__nextIsLocaleDomain); const jsxStyleRegistry = createStyleRegistry(); const ctx = { err, req: isAutoExport ? undefined : req, res: isAutoExport ? undefined : res, pathname, query, asPath, locale: renderOpts.locale, locales: renderOpts.locales, defaultLocale: renderOpts.defaultLocale, AppTree: (props)=>{ return React.createElement(AppContainer, null, React.createElement(App, { ...props, Component: Component, router: router })); }, defaultGetInitialProps: async (docCtx)=>{ const enhanceApp = (AppComp)=>{ return (props)=>React.createElement(AppComp, props); }; const { html, head } = await docCtx.renderPage({ enhanceApp }); const styles = jsxStyleRegistry.styles(); return { html, head, styles }; } }; let props; const ampState = { ampFirst: pageConfig.amp === true, hasQuery: Boolean(query.amp), hybrid: pageConfig.amp === "hybrid" }; const inAmpMode = isInAmpMode(ampState); const reactLoadableModules = []; let head = defaultHead(inAmpMode); let scriptLoader = {}; const nextExport = !isSSG && (renderOpts.nextExport || dev && (isAutoExport || isFallback)); const AppContainer = ({ children })=>React.createElement(RouterContext.Provider, { value: router }, React.createElement(AmpStateContext.Provider, { value: ampState }, React.createElement(HeadManagerContext.Provider, { value: { updateHead: (state)=>{ head = state; }, updateScripts: (scripts)=>{ scriptLoader = scripts; }, scripts: {}, mountedInstances: new Set() } }, React.createElement(LoadableContext.Provider, { value: (moduleName)=>reactLoadableModules.push(moduleName) }, React.createElement(StyleRegistry, { registry: jsxStyleRegistry }, children))))); props = await loadGetInitialProps(App, { AppTree: ctx.AppTree, Component, router, ctx }); if ((isSSG || getServerSideProps) && isPreview) { props.__N_PREVIEW = true; } if (isSSG) { props[STATIC_PROPS_ID] = true; } if (isSSG && !isFallback) { let data; try { data = await getStaticProps({ ...pageIsDynamic ? { params: query } : undefined, ...isPreview ? { preview: true, previewData: previewData } : undefined, locales: renderOpts.locales, locale: renderOpts.locale, defaultLocale: renderOpts.defaultLocale }); } catch (staticPropsError) { // remove not found error code to prevent triggering legacy // 404 rendering if (staticPropsError && staticPropsError.code === "ENOENT") { delete staticPropsError.code; } throw staticPropsError; } if (data == null) { throw new Error(GSP_NO_RETURNED_VALUE); } const invalidKeys = Object.keys(data).filter((key)=>key !== "revalidate" && key !== "props" && key !== "redirect" && key !== "notFound"); if (invalidKeys.includes("unstable_revalidate")) { throw new Error(UNSTABLE_REVALIDATE_RENAME_ERROR); } if (invalidKeys.length) { throw new Error(invalidKeysMsg("getStaticProps", invalidKeys)); } if (process.env.NODE_ENV !== "production") { if (typeof data.notFound !== "undefined" && typeof data.redirect !== "undefined") { throw new Error(`\`redirect\` and \`notFound\` can not both be returned from ${isSSG ? "getStaticProps" : "getServerSideProps"} at the same time. Page: ${pathname}\nSee more info here: https://nextjs.org/docs/messages/gssp-mixed-not-found-redirect`); } } if ("notFound" in data && data.notFound) { if (pathname === "/404") { throw new Error(`The /404 page can not return notFound in "getStaticProps", please remove it to continue!`); } renderOpts.isNotFound = true; } if ("redirect" in data && data.redirect && typeof data.redirect === "object") { checkRedirectValues(data.redirect, req, "getStaticProps"); if (isBuildTimeSSG) { throw new Error(`\`redirect\` can not be returned from getStaticProps during prerendering (${req.url})\n` + `See more info here: https://nextjs.org/docs/messages/gsp-redirect-during-prerender`); } data.props = { __N_REDIRECT: data.redirect.destination, __N_REDIRECT_STATUS: getRedirectStatus(data.redirect) }; if (typeof data.redirect.basePath !== "undefined") { data.props.__N_REDIRECT_BASE_PATH = data.redirect.basePath; } renderOpts.isRedirect = true; } if ((dev || isBuildTimeSSG) && !renderOpts.isNotFound && !isSerializableProps(pathname, "getStaticProps", data.props)) { // this fn should throw an error instead of ever returning `false` throw new Error("invariant: getStaticProps did not return valid props. Please report this."); } if ("revalidate" in data) { if (typeof data.revalidate === "number") { if (!Number.isInteger(data.revalidate)) { throw new Error(`A page's revalidate option must be seconds expressed as a natural number for ${req.url}. Mixed numbers, such as '${data.revalidate}', cannot be used.` + `\nTry changing the value to '${Math.ceil(data.revalidate)}' or using \`Math.ceil()\` if you're computing the value.`); } else if (data.revalidate <= 0) { throw new Error(`A page's revalidate option can not be less than or equal to zero for ${req.url}. A revalidate option of zero means to revalidate after _every_ request, and implies stale data cannot be tolerated.` + `\n\nTo never revalidate, you can set revalidate to \`false\` (only ran once at build-time).` + `\nTo revalidate as soon as possible, you can set the value to \`1\`.`); } else if (data.revalidate > 31536000) { // if it's greater than a year for some reason error console.warn(`Warning: A page's revalidate option was set to more than a year for ${req.url}. This may have been done in error.` + `\nTo only run getStaticProps at build-time and not revalidate at runtime, you can set \`revalidate\` to \`false\`!`); } } else if (data.revalidate === true) { // When enabled, revalidate after 1 second. This value is optimal for // the most up-to-date page possible, but without a 1-to-1 // request-refresh ratio. data.revalidate = 1; } else if (data.revalidate === false || typeof data.revalidate === "undefined") { // By default, we never revalidate. data.revalidate = false; } else { throw new Error(`A page's revalidate option must be seconds expressed as a natural number. Mixed numbers and strings cannot be used. Received '${JSON.stringify(data.revalidate)}' for ${req.url}`); } } else { // By default, we never revalidate. data.revalidate = false; } props.pageProps = Object.assign({}, props.pageProps, "props" in data ? data.props : undefined); // pass up revalidate and props for export // TODO: change this to a different passing mechanism renderOpts.revalidate = "revalidate" in data ? data.revalidate : undefined; renderOpts.pageData = props; // this must come after revalidate is added to renderOpts if (renderOpts.isNotFound) { return null; } } if (getServerSideProps) { props[SERVER_PROPS_ID] = true; } if (getServerSideProps && !isFallback) { let data; let canAccessRes = true; let resOrProxy = res; if (process.env.NODE_ENV !== "production") { resOrProxy = new Proxy(res, { get: function(obj, prop, receiver) { if (!canAccessRes) { throw new Error(`You should not access 'res' after getServerSideProps resolves.` + `\nRead more: https://nextjs.org/docs/messages/gssp-no-mutating-res`); } return Reflect.get(obj, prop, receiver); } }); } try { data = await getServerSideProps({ req: req, res: resOrProxy, query, resolvedUrl: renderOpts.resolvedUrl, ...pageIsDynamic ? { params: params } : undefined, ...previewData !== false ? { preview: true, previewData: previewData } : undefined, locales: renderOpts.locales, locale: renderOpts.locale, defaultLocale: renderOpts.defaultLocale }); canAccessRes = false; } catch (serverSidePropsError) { // remove not found error code to prevent triggering legacy // 404 rendering if (isError(serverSidePropsError) && serverSidePropsError.code === "ENOENT") { delete serverSidePropsError.code; } throw serverSidePropsError; } if (data == null) { throw new Error(GSSP_NO_RETURNED_VALUE); } const invalidKeys = Object.keys(data).filter((key)=>key !== "props" && key !== "redirect" && key !== "notFound"); if (data.unstable_notFound) { throw new Error(`unstable_notFound has been renamed to notFound, please update the field to continue. Page: ${pathname}`); } if (data.unstable_redirect) { throw new Error(`unstable_redirect has been renamed to redirect, please update the field to continue. Page: ${pathname}`); } if (invalidKeys.length) { throw new Error(invalidKeysMsg("getServerSideProps", invalidKeys)); } if ("notFound" in data && data.notFound) { if (pathname === "/404") { throw new Error(`The /404 page can not return notFound in "getStaticProps", please remove it to continue!`); } renderOpts.isNotFound = true; return null; } if ("redirect" in data && typeof data.redirect === "object") { checkRedirectValues(data.redirect, req, "getServerSideProps"); data.props = { __N_REDIRECT: data.redirect.destination, __N_REDIRECT_STATUS: getRedirectStatus(data.redirect) }; if (typeof data.redirect.basePath !== "undefined") { data.props.__N_REDIRECT_BASE_PATH = data.redirect.basePath; } renderOpts.isRedirect = true; } if (data.props instanceof Promise) { data.props = await data.props; } if ((dev || isBuildTimeSSG) && !isSerializableProps(pathname, "getServerSideProps", data.props)) { // this fn should throw an error instead of ever returning `false` throw new Error("invariant: getServerSideProps did not return valid props. Please report this."); } props.pageProps = Object.assign({}, props.pageProps, data.props); renderOpts.pageData = props; } if (!isSSG && // we only show this warning for legacy pages !getServerSideProps && process.env.NODE_ENV !== "production" && Object.keys(props?.pageProps || {}).includes("url")) { console.warn(`The prop \`url\` is a reserved prop in Next.js for legacy reasons and will be overridden on page ${pathname}\n` + `See more info here: https://nextjs.org/docs/messages/reserved-page-prop`); } // Avoid rendering page un-necessarily for getServerSideProps data request // and getServerSideProps/getStaticProps redirects if (isDataReq && !isSSG || renderOpts.isRedirect) { return RenderResult.fromStatic(JSON.stringify(props)); } // We don't call getStaticProps or getServerSideProps while generating // the fallback so make sure to set pageProps to an empty object if (isFallback) { props.pageProps = {}; } // the response might be finished on the getInitialProps call if (isResSent(res) && !isSSG) return null; // we preload the buildManifest for auto-export dynamic pages // to speed up hydrating query values let filteredBuildManifest = buildManifest; if (isAutoExport && pageIsDynamic) { const page = denormalizePagePath(normalizePagePath(pathname)); // This code would be much cleaner using `immer` and directly pushing into // the result from `getPageFiles`, we could maybe consider that in the // future. if (page in filteredBuildManifest.pages) { filteredBuildManifest = { ...filteredBuildManifest, pages: { ...filteredBuildManifest.pages, [page]: [ ...filteredBuildManifest.pages[page], ...filteredBuildManifest.lowPriorityFiles.filter((f)=>f.includes("_buildManifest")) ] }, lowPriorityFiles: filteredBuildManifest.lowPriorityFiles.filter((f)=>!f.includes("_buildManifest")) }; } } /** * Rules of Static & Dynamic HTML: * * 1.) We must generate static HTML unless the caller explicitly opts * in to dynamic HTML support. * * 2.) If dynamic HTML support is requested, we must honor that request * or throw an error. It is the sole responsibility of the caller to * ensure they aren't e.g. requesting dynamic HTML for an AMP page. * * These rules help ensure that other existing features like request caching, * coalescing, and ISR continue working as intended. */ const generateStaticHTML = supportsDynamicHTML !== true; const renderDocument = async ()=>{ if (Document.getInitialProps) { const renderPage = (options = {})=>{ if (ctx.err && ErrorDebug) { const html = ReactDOMServer.renderToString(React.createElement(ErrorDebug, { error: ctx.err })); return { html, head }; } if (dev && (props.router || props.Component)) { throw new Error(`'router' and 'Component' can not be returned in getInitialProps from _app.js https://nextjs.org/docs/messages/cant-override-next-props`); } const { App: EnhancedApp, Component: EnhancedComponent } = enhanceComponents(options, App, Component); const html = ReactDOMServer.renderToString(React.createElement(AppContainer, null, React.createElement(EnhancedApp, { Component: EnhancedComponent, router: router, ...props }))); return { html, head }; }; const documentCtx = { ...ctx, renderPage }; const docProps = await loadGetInitialProps(Document, documentCtx); // the response might be finished on the getInitialProps call if (isResSent(res) && !isSSG) return null; if (!docProps || typeof docProps.html !== "string") { const message = `"${getDisplayName(Document)}.getInitialProps()" should resolve to an object with a "html" prop set with a valid html string`; throw new Error(message); } return { bodyResult: piperFromArray([ docProps.html ]), documentElement: (htmlProps)=>React.createElement(Document, { ...htmlProps, ...docProps }), head: docProps.head, headTags: await headTags(documentCtx), styles: docProps.styles }; } else { const content = ctx.err && ErrorDebug ? React.createElement(ErrorDebug, { error: ctx.err }) : React.createElement(AppContainer, null, React.createElement(App, { ...props, Component: Component, router: router })); const bodyResult = concurrentFeatures ? await renderToStream(content, generateStaticHTML) : piperFromArray([ ReactDOMServer.renderToString(content) ]); return { bodyResult, documentElement: ()=>Document(), head, headTags: [], styles: jsxStyleRegistry.styles() }; } }; const documentResult = await renderDocument(); if (!documentResult) { return null; } const dynamicImportsIds = new Set(); const dynamicImports = new Set(); for (const mod of reactLoadableModules){ const manifestItem = reactLoadableManifest[mod]; if (manifestItem) { dynamicImportsIds.add(manifestItem.id); manifestItem.files.forEach((item)=>{ dynamicImports.add(item); }); } } const hybridAmp = ampState.hybrid; const docComponentsRendered = {}; const { assetPrefix, buildId, customServer, defaultLocale, disableOptimizedLoading, domainLocales, locale, locales, runtimeConfig } = renderOpts; const htmlProps = { __NEXT_DATA__: { props, page: pathname, query, buildId, assetPrefix: assetPrefix === "" ? undefined : assetPrefix, runtimeConfig, nextExport: nextExport === true ? true : undefined, autoExport: isAutoExport === true ? true : undefined, isFallback, dynamicIds: dynamicImportsIds.size === 0 ? undefined : Array.from(dynamicImportsIds), err: renderOpts.err ? serializeError(dev, renderOpts.err) : undefined, gsp: !!getStaticProps ? true : undefined, gssp: !!getServerSideProps ? true : undefined, customServer, gip: hasPageGetInitialProps ? true : undefined, appGip: !defaultAppGetInitialProps ? true : undefined, locale, locales, defaultLocale, domainLocales, isPreview: isPreview === true ? true : undefined }, buildManifest: filteredBuildManifest, docComponentsRendered, dangerousAsPath: router.asPath, canonicalBase: !renderOpts.ampPath && req.__nextStrippedLocale ? `${renderOpts.canonicalBase || ""}/${renderOpts.locale}` : renderOpts.canonicalBase, ampPath, inAmpMode, isDevelopment: !!dev, hybridAmp, dynamicImports: Array.from(dynamicImports), assetPrefix, // Only enabled in production as development mode has features relying on HMR (style injection for example) unstable_runtimeJS: process.env.NODE_ENV === "production" ? pageConfig.unstable_runtimeJS : undefined, unstable_JsPreload: pageConfig.unstable_JsPreload, devOnlyCacheBusterQueryString, scriptLoader, locale, disableOptimizedLoading, head: documentResult.head, headTags: documentResult.headTags, styles: documentResult.styles, useMaybeDeferContent }; const documentHTML = ReactDOMServer.renderToStaticMarkup(React.createElement(AmpStateContext.Provider, { value: ampState }, React.createElement(HtmlContext.Provider, { value: htmlProps }, documentResult.documentElement(htmlProps)))); if (process.env.NODE_ENV !== "production") { const nonRenderedComponents = []; const expectedDocComponents = [ "Main", "Head", "NextScript", "Html" ]; for (const comp of expectedDocComponents){ if (!docComponentsRendered[comp]) { nonRenderedComponents.push(comp); } } const plural = nonRenderedComponents.length !== 1 ? "s" : ""; if (nonRenderedComponents.length) { const missingComponentList = nonRenderedComponents.map((e)=>`<${e} />`).join(", "); warn(`Your custom Document (pages/_document) did not render all the required subcomponent${plural}.\n` + `Missing component${plural}: ${missingComponentList}\n` + "Read how to fix here: https://nextjs.org/docs/messages/missing-document-component"); } } const renderTargetIdx = documentHTML.indexOf(BODY_RENDER_TARGET); const prefix = []; prefix.push("<!DOCTYPE html>"); prefix.push(documentHTML.substring(0, renderTargetIdx)); if (inAmpMode) { prefix.push("<!-- __NEXT_DATA__ -->"); } let pipers = [ piperFromArray(prefix), documentResult.bodyResult, piperFromArray([ documentHTML.substring(renderTargetIdx + BODY_RENDER_TARGET.length) ]) ]; const postProcessors = (generateStaticHTML ? [ inAmpMode ? async (html)=>{ html = await optimizeAmp(html, renderOpts.ampOptimizerConfig); if (!renderOpts.ampSkipValidation && renderOpts.ampValidator) { await renderOpts.ampValidator(html, pathname); } return html; } : null, process.env.__NEXT_OPTIMIZE_FONTS || process.env.__NEXT_OPTIMIZE_IMAGES ? async (html)=>{ return await postProcess(html, { getFontDefinition }, { optimizeFonts: renderOpts.optimizeFonts, optimizeImages: renderOpts.optimizeImages }); } : null, renderOpts.optimizeCss ? async (html)=>{ // eslint-disable-next-line import/no-extraneous-dependencies const Critters = require("critters"); const cssOptimizer = new Critters({ ssrMode: true, reduceInlineStyles: false, path: renderOpts.distDir, publicPath: `${renderOpts.assetPrefix}/_next/`, preload: "media", fonts: false, ...renderOpts.optimizeCss }); return await cssOptimizer.process(html); } : null, inAmpMode || hybridAmp ? async (html)=>{ return html.replace(/&amp;amp=1/g, "&amp=1"); } : null ] : []).filter(Boolean); if (generateStaticHTML || postProcessors.length > 0) { let html = await piperToString(chainPipers(pipers)); for (const postProcessor of postProcessors){ if (postProcessor) { html = await postProcessor(html); } } return new RenderResult(html); } return new RenderResult(chainPipers(pipers)); } function errorToJSON(err) { const { name, message, stack } = err; return { name, message, stack }; } function serializeError(dev, err) { if (dev) { return errorToJSON(err); } return { name: "Internal Server Error.", message: "500 - Internal Server Error.", statusCode: 500 }; } function renderToStream(element, generateStaticHTML) { return new Promise((resolve, reject)=>{ let underlyingStream = null; const stream = new Writable({ // Use the buffer from the underlying stream highWaterMark: 0, write (chunk, encoding, callback) { if (!underlyingStream) { throw new Error("invariant: write called without an underlying stream. This is a bug in Next.js"); } if (!underlyingStream.writable.write(chunk, encoding)) { underlyingStream.queuedCallbacks.push(()=>callback()); } else { callback(); } } }); stream.once("finish", ()=>{ if (!underlyingStream) { throw new Error("invariant: finish called without an underlying stream. This is a bug in Next.js"); } underlyingStream.resolve(); }); stream.once("error", (err)=>{ if (!underlyingStream) { throw new Error("invariant: error called without an underlying stream. This is a bug in Next.js"); } underlyingStream.resolve(err); }); // React uses `flush` to prevent stream middleware like gzip from buffering to the // point of harming streaming performance, so we make sure to expose it and forward it. // See: https://github.com/reactwg/react-18/discussions/91 Object.defineProperty(stream, "flush", { value: ()=>{ if (!underlyingStream) { throw new Error("invariant: flush called without an underlying stream. This is a bug in Next.js"); } if (typeof underlyingStream.writable.flush === "function") { underlyingStream.writable.flush(); } }, enumerable: true }); let resolved = false; const doResolve = ()=>{ if (!resolved) { resolved = true; resolve((res, next)=>{ const drainHandler = ()=>{ const prevCallbacks = underlyingStream.queuedCallbacks; underlyingStream.queuedCallbacks = []; prevCallbacks.forEach((callback)=>callback()); }; res.on("drain", drainHandler); underlyingStream = { resolve: (err)=>{ underlyingStream = null; res.removeListener("drain", drainHandler); next(err); }, writable: res, queuedCallbacks: [] }; startWriting(); }); } }; const { abort, startWriting } = ReactDOMServer.pipeToNodeWritable(element, stream, { onError (error) { if (!resolved) { resolved = true; reject(error); } abort(); }, onCompleteShell () { if (!generateStaticHTML) { doResolve(); } }, onCompleteAll () { doResolve(); } }); }); } function chainPipers(pipers) { return pipers.reduceRight((lhs, rhs)=>(res, next)=>{ rhs(res, (err)=>err ? next(err) : lhs(res, next)); }, (res, next)=>{ res.end(); next(); }); } function piperFromArray(chunks) { return (res, next)=>{ if (typeof res.cork === "function") { res.cork(); } chunks.forEach((chunk)=>res.write(chunk)); if (typeof res.uncork === "function") { res.uncork(); } next(); }; } function piperToString(input) { return new Promise((resolve, reject)=>{ const bufferedChunks = []; const stream = new Writable({ writev (chunks, callback) { chunks.forEach((chunk)=>bufferedChunks.push(chunk.chunk)); callback(); } }); input(stream, (err)=>{ if (err) { reject(err); } else { resolve(Buffer.concat(bufferedChunks).toString()); } }); }); } export function useMaybeDeferContent(_name, contentFn) { return [ false, contentFn() ]; }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/fixture/private-method-overload-and-abstract/input.ts
TypeScript
class test { #test(); #test() { } abstract #test(); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/fixture/private-method-overload-and-abstract/output.js
JavaScript
var _test = /*#__PURE__*/ new WeakSet(); class test { constructor(){ _class_private_method_init(this, _test); } } function test1() {}
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/fixture/web-969/1/input.ts
TypeScript
import { NextResponse } from "next/server"; export async function GET(): Promise<Response> { return NextResponse.json({ data: "hello" }); } export type { NextResponse };
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/fixture/web-969/1/output.js
JavaScript
import { NextResponse } from "next/server"; export async function GET() { return NextResponse.json({ data: "hello" }); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/strip.rs
Rust
use std::path::PathBuf; use swc_common::{comments::NoopComments, pass::Optional, Mark}; use swc_ecma_ast::Pass; use swc_ecma_parser::{Syntax, TsSyntax}; use swc_ecma_transforms_base::resolver; use swc_ecma_transforms_compat::{ class_fields_use_set::class_fields_use_set, es2015::{block_scoping, destructuring, parameters}, es2017::async_to_generator, es2020::{nullish_coalescing, optional_chaining}, es2022::{class_properties, static_blocks}, }; use swc_ecma_transforms_proposal::decorators; use swc_ecma_transforms_react::jsx; use swc_ecma_transforms_testing::{test, test_exec, test_fixture, Tester}; use swc_ecma_transforms_typescript::{ tsx, typescript, ImportsNotUsedAsValues, TsImportExportAssignConfig, TsxConfig, }; fn tr(t: &mut Tester) -> impl Pass { tr_config(t, None, None, false) } fn tr_config( t: &mut Tester, config: Option<typescript::Config>, decorators_config: Option<decorators::Config>, use_define_for_class_fields: bool, ) -> impl Pass { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); let has_decorators = decorators_config.is_some(); let config = config.unwrap_or_else(|| typescript::Config { no_empty_export: true, ..Default::default() }); ( Optional::new( decorators(decorators_config.unwrap_or_default()), has_decorators, ), resolver(unresolved_mark, top_level_mark, true), typescript(config, unresolved_mark, top_level_mark), jsx( t.cm.clone(), None::<NoopComments>, Default::default(), top_level_mark, unresolved_mark, ), Optional::new(class_fields_use_set(true), !use_define_for_class_fields), ) } fn tsxr(t: &Tester) -> impl Pass { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), tsx( t.cm.clone(), typescript::Config { no_empty_export: true, import_not_used_as_values: ImportsNotUsedAsValues::Remove, ..Default::default() }, TsxConfig::default(), t.comments.clone(), unresolved_mark, top_level_mark, ), swc_ecma_transforms_react::jsx( t.cm.clone(), Some(t.comments.clone()), swc_ecma_transforms_react::Options::default(), top_level_mark, unresolved_mark, ), ) } fn properties(_: &Tester, loose: bool) -> impl Pass { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), static_blocks(), class_properties( class_properties::Config { set_public_fields: loose, ..Default::default() }, unresolved_mark, ), ) } macro_rules! to { ($name:ident, $from:expr) => { test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |t| (tr(t), properties(t, true)), $name, $from ); }; } macro_rules! test_with_config { ($name:ident, $config:expr, SET, $from:expr) => { test_with_config!($name, $config, false, $from); }; ($name:ident, $config:expr, $from:expr) => { test_with_config!($name, $config, true, $from); }; ($name:ident, $config:expr, $use_define:expr,$from:expr) => { test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |t| tr_config(t, Some($config), None, $use_define), $name, $from ); }; } test!( Syntax::Typescript(Default::default()), |t| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, true), tr(t), parameters( parameters::Config { ignore_function_length: true, }, unresolved_mark, ), destructuring(destructuring::Config { loose: false }), block_scoping(unresolved_mark), ) }, fn_len_default_assignment_with_types, "export function transformFileSync( filename: string, opts: Object = {}, ): string {}" ); // TODO: Test function / variable hoisting test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, issue_392_2, " import { PlainObject } from 'simplytyped'; const dict: PlainObject = {}; " ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, issue_461, "for (let x in ['']) { (x => 0)(x); }" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, issue_468_1, "tView.firstCreatePass ? getOrCreateTNode(tView, lView[T_HOST], index, TNodeType.Element, null, null) : tView.data[adjustedIndex] as TElementNode" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, issue_468_2, "tView.firstCreatePass ? getOrCreateTNode(tView, lView[T_HOST], index, TNodeType.Element, null, null) : tView.data[adjustedIndex] as TElementNode" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, issue_468_3, "tView.firstCreatePass ? getOrCreateTNode() : tView.data[adjustedIndex] as TElementNode" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, issue_468_4, "a ? b : c" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, issue_468_5, "a ? b : c as T" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, issue_468_6, "a.b ? c() : d.e[f] as T" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, issue_468_7, "tView.firstCreatePass ? getOrCreateTNode() : tView.data[adjustedIndex]" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, enum_simple, "enum Foo{ a }" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, enum_str, "enum State { closed = 'closed', opened = 'opened', mounted = 'mounted', unmounted = 'unmounted', }" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, enum_key_value, "enum StateNum { closed = 'cl0', opened = 'op1', mounted = 'mo2', }" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, enum_export_str, "export enum State { closed = 'closed', opened = 'opened', mounted = 'mounted', unmounted = 'unmounted', }" ); to!( enum_self_reference, "var x; enum Foo { a, b = a, c = b + 1, d = c }" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, issue_640, "import { Handler } from 'aws-lambda'; export const handler: Handler = async (event, context) => {};" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, issue_656, "export const x = { text: 'hello' } as const;" ); to!(import_type, "import type foo from 'foo'"); to!(export_type, "export type { foo }"); to!( issue_685, " type MyType = string; export default MyType;" ); to!( issue_685_2, " class MyType {} type MyType = string; export default MyType;" ); to!( issue_685_3, " var MyType = function(){}; type MyType = string; export default MyType;" ); to!( issue_685_4, " interface MyType { other: number; } export default MyType;" ); to!( ts_enum_str_init, "enum FlexSize { md = 'md', lg = 'lg', }" ); to!( ts_enum_no_init, "enum FlexSize { md, lg, }" ); to!(module_01, "module 'foo'{ }"); to!(declare_01, "declare var env: FOO"); to!( issue_757, "// test.ts enum Foo { A, B, } export default Foo; " ); to!( issue_786_1, "import { IPerson } from '../types/types' export function createPerson(person: IPerson) { const a = {} as IPerson }" ); to!( issue_786_2, "import { IPerson } from '../types/types' function createPerson(person: IPerson) { const a = {} as IPerson }" ); to!( issue_791_1, "import { IPerson } from '../types/types' export interface IEmployee extends IPerson { } export function createPerson(person: IPerson) { const a = {} as IPerson }" ); to!( issue_791_2, "import { IPerson } from '../types/types' export class Employee implements IPerson { } export function createPerson(person: IPerson) { const a = {} as IPerson }" ); to!( issue_791_3, "import { IPerson } from '../types/types' export type MyPerson = IPerson; export function createPerson(person: MyPerson) { const a = {} as MyPerson }" ); to!( issue_791_4, "import { A, B } from '../types/types' export class Child extends A implements B { }" ); to!( issue_793_1, "import { IPerson } from '../types/types' export function createPerson(person) { const a = {} as IPerson }" ); to!( issue_793_2, "import { IPerson } from '../types/types' export function createPerson(person) { const a = <IPerson>{}; }" ); to!( issue_900_1, "export class FeatureSet<Name extends string> { log(a: Name) { console.log(a) } }" ); to!( issue_900_2, "class FeatureSet<Name extends string> { log(a: Name) { console.log(a) } }" ); to!( issue_900_3, "export default class FeatureSet<Name extends string> { log(a: Name) { console.log(a) } }" ); to!( issue_820_1, "enum Direction { Up = 1, Down = 2, Left = Up + Down, }" ); to!( issue_915, "export class Logger { #level: LogLevels; #handlers: BaseHandler[]; readonly #loggerName: string; constructor( loggerName: string, levelName: LevelName, options: LoggerOptions = {}, ) { this.#loggerName = loggerName; this.#level = getLevelByName(levelName); this.#handlers = options.handlers || []; } }" ); to!( issue_915_2, r#"Deno.test("[ws] WebSocket should act as asyncIterator", async () => { enum Frames { ping, hello, close, end, } });"# ); to!( issue_915_3, r#"export class MultipartReader { readonly newLine = encoder.encode("\r\n"); }"# ); to!( issue_912, r#"export class BadRequestError extends Error { constructor(public readonly message: string) { super(message) } }"# ); to!( issue_921, "export abstract class Kernel { [key: string]: any }" ); to!( issue_926, "class A extends Object { constructor(public a, private b) { super(); } }" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, issue_930_instance, "class A { b = this.a; constructor(readonly a){ } }" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), |t| (tr(t), properties(t, true)), issue_930_static, "class A { static b = 'foo'; constructor(a){ } }" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), |t| (tr(t), properties(t, true)), typescript_001, "class A { foo = new Subject() constructor() { this.foo.subscribe() } }" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, typescript_002, "class A extends B { foo = 'foo' b = this.a; declare1 declare2!: string constructor(private readonly a: string, readonly c, private d: number = 1) { super() this.foo.subscribe() } }" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, issue_958, "export class Test { constructor(readonly test?: string) {} }" ); test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |t| ( decorators(decorators::Config { legacy: true, ..Default::default() }), tr(t) ), issue_960_1, " function DefineAction() { return (target, property) => { console.log(target, property); } } class Base { constructor() { this.action = new Subject() } } class Child extends Base { @DefineAction() action: Observable<void> callApi() { console.log(this.action) // undefined } } " ); test_exec!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |t| ( decorators(decorators::Config { legacy: true, ..Default::default() }), tr(t) ), issue_960_2, "function DefineAction() { return function(_a, _b, c) { return c } } class Base { constructor() { this.action = 1 } } class Child extends Base { @DefineAction() declare action: number callApi() { console.log(this.action) // undefined return this.action } } const c = new Child() c.callApi() expect(c.callApi()).not.toBe(undefined) expect(c.action).toBe(1); " ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, issue_1032, r#"import { indent as indentFormatter, newline as newlineFormatter, breakpoint as breakpointFormatter, } from "./format.ts"; const proseTypes = new Map(); // deno-lint-ignore ban-types const prose = (l: number, i: Function, nl: Function, bp: string): string => { return i(l) + bp + "prose {" + nl + i(l + 1) + "color: #374151;" + nl + i(l + 1) + "max-width: 65ch;" + nl + i(l) + "}" + nl + i(l) + bp + 'prose [class~="lead"] {' + nl + i(l + 1) + "color: #4b5563;" + nl + i(l + 1) + "font-size: 1.25em;" + nl + i(l + 1) + "line-height: 1.6;" + nl + i(l + 1) + "margin-top: 1.2em;" + nl + i(l + 1) + "margin-bottom: 1.2em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose a {" + nl + i(l + 1) + "color: #5850ec;" + nl + i(l + 1) + "text-decoration: none;" + nl + i(l + 1) + "font-weight: 600;" + nl + i(l) + "}" + nl + i(l) + bp + "prose strong {" + nl + i(l + 1) + "color: #161e2e;" + nl + i(l + 1) + "font-weight: 600;" + nl + i(l) + "}" + nl + i(l) + bp + "prose ol {" + nl + i(l + 1) + "counter-reset: list-counter;" + nl + i(l + 1) + "margin-top: 1.25em;" + nl + i(l + 1) + "margin-bottom: 1.25em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose ol > li {" + nl + i(l + 1) + "position: relative;" + nl + i(l + 1) + "counter-increment: list-counter;" + nl + i(l + 1) + "padding-left: 1.75em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose ol > li::before {" + nl + i(l + 1) + 'content: counter(list-counter) ".";' + nl + i(l + 1) + "position: absolute;" + nl + i(l + 1) + "font-weight: 400;" + nl + i(l + 1) + "color: #6b7280;" + nl + i(l) + "}" + nl + i(l) + bp + "prose ul > li {" + nl + i(l + 1) + "position: relative;" + nl + i(l + 1) + "padding-left: 1.75em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose ul > li::before {" + nl + i(l + 1) + 'content: "";' + nl + i(l + 1) + "position: absolute;" + nl + i(l + 1) + "background-color: #d2d6dc;" + nl + i(l + 1) + "border-radius: 50%;" + nl + i(l + 1) + "width: 0.375em;" + nl + i(l + 1) + "height: 0.375em;" + nl + i(l + 1) + "top: calc(0.875em - 0.1875em);" + nl + i(l + 1) + "left: 0.25em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose hr {" + nl + i(l + 1) + "border-color: #e5e7eb;" + nl + i(l + 1) + "border-top-width: 1px;" + nl + i(l + 1) + "margin-top: 3em;" + nl + i(l + 1) + "margin-bottom: 3em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose blockquote {" + nl + i(l + 1) + "font-weight: 500;" + nl + i(l + 1) + "font-style: italic;" + nl + i(l + 1) + "color: #161e2e;" + nl + i(l + 1) + "border-left-width: 0.25rem;" + nl + i(l + 1) + "border-left-color: #e5e7eb;" + nl + i(l + 1) + 'quotes: "\\201C""\\201D""\\2018""\\2019";' + nl + i(l + 1) + "margin-top: 1.6em;" + nl + i(l + 1) + "margin-bottom: 1.6em;" + nl + i(l + 1) + "padding-left: 1em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose blockquote p:first-of-type::before {" + nl + i(l + 1) + "content: open-quote;" + nl + i(l) + "}" + nl + i(l) + bp + "prose blockquote p:last-of-type::after {" + nl + i(l + 1) + "content: close-quote;" + nl + i(l) + "}" + nl + i(l) + bp + "prose h1 {" + nl + i(l + 1) + "color: #1a202c;" + nl + i(l + 1) + "font-weight: 800;" + nl + i(l + 1) + "font-size: 2.25em;" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l + 1) + "margin-bottom: 0.8888889em;" + nl + i(l + 1) + "line-height: 1.1111111;" + nl + i(l) + "}" + nl + i(l) + bp + "prose h2 {" + nl + i(l + 1) + "color: #1a202c;" + nl + i(l + 1) + "font-weight: 700;" + nl + i(l + 1) + "font-size: 1.5em;" + nl + i(l + 1) + "margin-top: 2em;" + nl + i(l + 1) + "margin-bottom: 1em;" + nl + i(l + 1) + "line-height: 1.3333333;" + nl + i(l) + "}" + nl + i(l) + bp + "prose h3 {" + nl + i(l + 1) + "color: #1a202c;" + nl + i(l + 1) + "font-weight: 600;" + nl + i(l + 1) + "font-size: 1.25em;" + nl + i(l + 1) + "margin-top: 1.6em;" + nl + i(l + 1) + "margin-bottom: 0.6em;" + nl + i(l + 1) + "line-height: 1.6;" + nl + i(l) + "}" + nl + i(l) + bp + "prose h4 {" + nl + i(l + 1) + "color: #1a202c;" + nl + i(l + 1) + "font-weight: 600;" + nl + i(l + 1) + "margin-top: 1.5em;" + nl + i(l + 1) + "margin-bottom: 0.5em;" + nl + i(l + 1) + "line-height: 1.5;" + nl + i(l) + "}" + nl + i(l) + bp + "prose figure figcaption {" + nl + i(l + 1) + "color: #6b7280;" + nl + i(l + 1) + "font-size: 0.875em;" + nl + i(l + 1) + "line-height: 1.4285714;" + nl + i(l + 1) + "margin-top: 0.8571429em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose code {" + nl + i(l + 1) + "color: #161e2e;" + nl + i(l + 1) + "font-weight: 600;" + nl + i(l + 1) + "font-size: 0.875em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose code::before {" + nl + i(l + 1) + 'content: "`";' + nl + i(l) + "}" + nl + i(l) + bp + "prose code::after {" + nl + i(l + 1) + 'content: "`";' + nl + i(l) + "}" + nl + i(l) + bp + "prose pre {" + nl + i(l + 1) + "color: #e5e7eb;" + nl + i(l + 1) + "background-color: #252f3f;" + nl + i(l + 1) + "overflow-x: auto;" + nl + i(l + 1) + "font-size: 0.875em;" + nl + i(l + 1) + "line-height: 1.7142857;" + nl + i(l + 1) + "margin-top: 1.7142857em;" + nl + i(l + 1) + "margin-bottom: 1.7142857em;" + nl + i(l + 1) + "border-radius: 0.375rem;" + nl + i(l + 1) + "padding-top: 0.8571429em;" + nl + i(l + 1) + "padding-right: 1.1428571em;" + nl + i(l + 1) + "padding-bottom: 0.8571429em;" + nl + i(l + 1) + "padding-left: 1.1428571em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose pre code {" + nl + i(l + 1) + "background-color: transparent;" + nl + i(l + 1) + "border-width: 0;" + nl + i(l + 1) + "border-radius: 0;" + nl + i(l + 1) + "padding: 0;" + nl + i(l + 1) + "font-weight: 400;" + nl + i(l + 1) + "color: inherit;" + nl + i(l + 1) + "font-size: inherit;" + nl + i(l + 1) + "font-family: inherit;" + nl + i(l + 1) + "line-height: inherit;" + nl + i(l) + "}" + nl + i(l) + bp + "prose pre code::before {" + nl + i(l + 1) + 'content: "";' + nl + i(l) + "}" + nl + i(l) + bp + "prose pre code::after {" + nl + i(l + 1) + 'content: "";' + nl + i(l) + "}" + nl + i(l) + bp + "prose table {" + nl + i(l + 1) + "width: 100%;" + nl + i(l + 1) + "table-layout: auto;" + nl + i(l + 1) + "text-align: left;" + nl + i(l + 1) + "margin-top: 2em;" + nl + i(l + 1) + "margin-bottom: 2em;" + nl + i(l + 1) + "font-size: 0.875em;" + nl + i(l + 1) + "line-height: 1.7142857;" + nl + i(l) + "}" + nl + i(l) + bp + "prose thead {" + nl + i(l + 1) + "color: #161e2e;" + nl + i(l + 1) + "font-weight: 600;" + nl + i(l + 1) + "border-bottom-width: 1px;" + nl + i(l + 1) + "border-bottom-color: #d2d6dc;" + nl + i(l) + "}" + nl + i(l) + bp + "prose thead th {" + nl + i(l + 1) + "vertical-align: bottom;" + nl + i(l + 1) + "padding-right: 0.5714286em;" + nl + i(l + 1) + "padding-bottom: 0.5714286em;" + nl + i(l + 1) + "padding-left: 0.5714286em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose tbody tr {" + nl + i(l + 1) + "border-bottom-width: 1px;" + nl + i(l + 1) + "border-bottom-color: #e5e7eb;" + nl + i(l) + "}" + nl + i(l) + bp + "prose tbody tr:last-child {" + nl + i(l + 1) + "border-bottom-width: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose tbody td {" + nl + i(l + 1) + "vertical-align: top;" + nl + i(l + 1) + "padding-top: 0.5714286em;" + nl + i(l + 1) + "padding-right: 0.5714286em;" + nl + i(l + 1) + "padding-bottom: 0.5714286em;" + nl + i(l + 1) + "padding-left: 0.5714286em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose {" + nl + i(l + 1) + "font-size: 1rem;" + nl + i(l + 1) + "line-height: 1.75;" + nl + i(l) + "}" + nl + i(l) + bp + "prose p {" + nl + i(l + 1) + "margin-top: 1.25em;" + nl + i(l + 1) + "margin-bottom: 1.25em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose img {" + nl + i(l + 1) + "margin-top: 2em;" + nl + i(l + 1) + "margin-bottom: 2em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose video {" + nl + i(l + 1) + "margin-top: 2em;" + nl + i(l + 1) + "margin-bottom: 2em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose figure {" + nl + i(l + 1) + "margin-top: 2em;" + nl + i(l + 1) + "margin-bottom: 2em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose figure > * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l + 1) + "margin-bottom: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose h2 code {" + nl + i(l + 1) + "font-size: 0.875em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose h3 code {" + nl + i(l + 1) + "font-size: 0.9em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose ul {" + nl + i(l + 1) + "margin-top: 1.25em;" + nl + i(l + 1) + "margin-bottom: 1.25em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose li {" + nl + i(l + 1) + "margin-top: 0.5em;" + nl + i(l + 1) + "margin-bottom: 0.5em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose ol > li:before {" + nl + i(l + 1) + "left: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose > ul > li p {" + nl + i(l + 1) + "margin-top: 0.75em;" + nl + i(l + 1) + "margin-bottom: 0.75em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose > ul > li > :first-child {" + nl + i(l + 1) + "margin-top: 1.25em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose > ul > li > :last-child {" + nl + i(l + 1) + "margin-bottom: 1.25em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose > ol > li > :first-child {" + nl + i(l + 1) + "margin-top: 1.25em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose > ol > li > :last-child {" + nl + i(l + 1) + "margin-bottom: 1.25em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose ol ol," + nl + i(l) + bp + "prose ol ul," + nl + i(l) + bp + "prose ul ol," + nl + i(l) + bp + "prose ul ul {" + nl + i(l + 1) + "margin-top: 0.75em;" + nl + i(l + 1) + "margin-bottom: 0.75em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose hr + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose h2 + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose h3 + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose h4 + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose thead th:first-child {" + nl + i(l + 1) + "padding-left: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose thead th:last-child {" + nl + i(l + 1) + "padding-right: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose tbody td:first-child {" + nl + i(l + 1) + "padding-left: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose tbody td:last-child {" + nl + i(l + 1) + "padding-right: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose > :first-child {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose > :last-child {" + nl + i(l + 1) + "margin-bottom: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose h1," + nl + i(l) + bp + "prose h2," + nl + i(l) + bp + "prose h3," + nl + i(l) + bp + "prose h4 {" + nl + i(l + 1) + "color: #161e2e;" + nl + i(l) + "}" + nl; }; proseTypes.set("prose", prose); // deno-lint-ignore ban-types const proseSm = (l: number, i: Function, nl: Function, bp: string): string => { return i(l) + bp + "prose-sm {" + nl + i(l + 1) + "font-size: 0.875rem;" + nl + i(l + 1) + "line-height: 1.7142857;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm p {" + nl + i(l + 1) + "margin-top: 1.1428571em;" + nl + i(l + 1) + "margin-bottom: 1.1428571em;" + nl + i(l) + "}" + nl + i(l) + bp + 'prose-sm [class~="lead"] {' + nl + i(l + 1) + "font-size: 1.2857143em;" + nl + i(l + 1) + "line-height: 1.5555556;" + nl + i(l + 1) + "margin-top: 0.8888889em;" + nl + i(l + 1) + "margin-bottom: 0.8888889em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm blockquote {" + nl + i(l + 1) + "margin-top: 1.3333333em;" + nl + i(l + 1) + "margin-bottom: 1.3333333em;" + nl + i(l + 1) + "padding-left: 1.1111111em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm h1 {" + nl + i(l + 1) + "font-size: 2.1428571em;" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l + 1) + "margin-bottom: 0.8em;" + nl + i(l + 1) + "line-height: 1.2;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm h2 {" + nl + i(l + 1) + "font-size: 1.4285714em;" + nl + i(l + 1) + "margin-top: 1.6em;" + nl + i(l + 1) + "margin-bottom: 0.8em;" + nl + i(l + 1) + "line-height: 1.4;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm h3 {" + nl + i(l + 1) + "font-size: 1.2857143em;" + nl + i(l + 1) + "margin-top: 1.5555556em;" + nl + i(l + 1) + "margin-bottom: 0.4444444em;" + nl + i(l + 1) + "line-height: 1.5555556;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm h4 {" + nl + i(l + 1) + "margin-top: 1.4285714em;" + nl + i(l + 1) + "margin-bottom: 0.5714286em;" + nl + i(l + 1) + "line-height: 1.4285714;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm img {" + nl + i(l + 1) + "margin-top: 1.7142857em;" + nl + i(l + 1) + "margin-bottom: 1.7142857em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm video {" + nl + i(l + 1) + "margin-top: 1.7142857em;" + nl + i(l + 1) + "margin-bottom: 1.7142857em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm figure {" + nl + i(l + 1) + "margin-top: 1.7142857em;" + nl + i(l + 1) + "margin-bottom: 1.7142857em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm figure > * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l + 1) + "margin-bottom: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm figure figcaption {" + nl + i(l + 1) + "font-size: 0.8571429em;" + nl + i(l + 1) + "line-height: 1.3333333;" + nl + i(l + 1) + "margin-top: 0.6666667em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm code {" + nl + i(l + 1) + "font-size: 0.8571429em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm h2 code {" + nl + i(l + 1) + "font-size: 0.9em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm h3 code {" + nl + i(l + 1) + "font-size: 0.8888889em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm pre {" + nl + i(l + 1) + "font-size: 0.8571429em;" + nl + i(l + 1) + "line-height: 1.6666667;" + nl + i(l + 1) + "margin-top: 1.6666667em;" + nl + i(l + 1) + "margin-bottom: 1.6666667em;" + nl + i(l + 1) + "border-radius: 0.25rem;" + nl + i(l + 1) + "padding-top: 0.6666667em;" + nl + i(l + 1) + "padding-right: 1em;" + nl + i(l + 1) + "padding-bottom: 0.6666667em;" + nl + i(l + 1) + "padding-left: 1em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm ol {" + nl + i(l + 1) + "margin-top: 1.1428571em;" + nl + i(l + 1) + "margin-bottom: 1.1428571em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm ul {" + nl + i(l + 1) + "margin-top: 1.1428571em;" + nl + i(l + 1) + "margin-bottom: 1.1428571em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm li {" + nl + i(l + 1) + "margin-top: 0.2857143em;" + nl + i(l + 1) + "margin-bottom: 0.2857143em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm ol > li {" + nl + i(l + 1) + "padding-left: 1.5714286em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm ol > li:before {" + nl + i(l + 1) + "left: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm ul > li {" + nl + i(l + 1) + "padding-left: 1.5714286em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm ul > li::before {" + nl + i(l + 1) + "height: 0.3571429em;" + nl + i(l + 1) + "width: 0.3571429em;" + nl + i(l + 1) + "top: calc(0.8571429em - 0.1785714em);" + nl + i(l + 1) + "left: 0.2142857em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm > ul > li p {" + nl + i(l + 1) + "margin-top: 0.5714286em;" + nl + i(l + 1) + "margin-bottom: 0.5714286em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm > ul > li > :first-child {" + nl + i(l + 1) + "margin-top: 1.1428571em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm > ul > li > :last-child {" + nl + i(l + 1) + "margin-bottom: 1.1428571em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm > ol > li > :first-child {" + nl + i(l + 1) + "margin-top: 1.1428571em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm > ol > li > :last-child {" + nl + i(l + 1) + "margin-bottom: 1.1428571em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm ol ol," + nl + i(l) + bp + "prose-sm ol ul," + nl + i(l) + bp + "prose-sm ul ol," + nl + i(l) + bp + "prose-sm ul ul {" + nl + i(l + 1) + "margin-top: 0.5714286em;" + nl + i(l + 1) + "margin-bottom: 0.5714286em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm hr {" + nl + i(l + 1) + "margin-top: 2.8571429em;" + nl + i(l + 1) + "margin-bottom: 2.8571429em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm hr + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm h2 + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm h3 + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm h4 + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm table {" + nl + i(l + 1) + "font-size: 0.8571429em;" + nl + i(l + 1) + "line-height: 1.5;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm thead th {" + nl + i(l + 1) + "padding-right: 1em;" + nl + i(l + 1) + "padding-bottom: 0.6666667em;" + nl + i(l + 1) + "padding-left: 1em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm thead th:first-child {" + nl + i(l + 1) + "padding-left: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm thead th:last-child {" + nl + i(l + 1) + "padding-right: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm tbody td {" + nl + i(l + 1) + "padding-top: 0.6666667em;" + nl + i(l + 1) + "padding-right: 1em;" + nl + i(l + 1) + "padding-bottom: 0.6666667em;" + nl + i(l + 1) + "padding-left: 1em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm tbody td:first-child {" + nl + i(l + 1) + "padding-left: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm tbody td:last-child {" + nl + i(l + 1) + "padding-right: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm > :first-child {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-sm > :last-child {" + nl + i(l + 1) + "margin-bottom: 0;" + nl + i(l) + "}" + nl; }; proseTypes.set("prose-sm", proseSm); // deno-lint-ignore ban-types const proseLg = (l: number, i: Function, nl: Function, bp: string): string => { return i(l) + bp + "prose-lg {" + nl + i(l + 1) + "font-size: 1.125rem;" + nl + i(l + 1) + "line-height: 1.7777778;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg p {" + nl + i(l + 1) + "margin-top: 1.3333333em;" + nl + i(l + 1) + "margin-bottom: 1.3333333em;" + nl + i(l) + "}" + nl + i(l) + bp + 'prose-lg [class~="lead"] {' + nl + i(l + 1) + "font-size: 1.2222222em;" + nl + i(l + 1) + "line-height: 1.4545455;" + nl + i(l + 1) + "margin-top: 1.0909091em;" + nl + i(l + 1) + "margin-bottom: 1.0909091em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg blockquote {" + nl + i(l + 1) + "margin-top: 1.6666667em;" + nl + i(l + 1) + "margin-bottom: 1.6666667em;" + nl + i(l + 1) + "padding-left: 1em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg h1 {" + nl + i(l + 1) + "font-size: 2.6666667em;" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l + 1) + "margin-bottom: 0.8333333em;" + nl + i(l + 1) + "line-height: 1;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg h2 {" + nl + i(l + 1) + "font-size: 1.6666667em;" + nl + i(l + 1) + "margin-top: 1.8666667em;" + nl + i(l + 1) + "margin-bottom: 1.0666667em;" + nl + i(l + 1) + "line-height: 1.3333333;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg h3 {" + nl + i(l + 1) + "font-size: 1.3333333em;" + nl + i(l + 1) + "margin-top: 1.6666667em;" + nl + i(l + 1) + "margin-bottom: 0.6666667em;" + nl + i(l + 1) + "line-height: 1.5;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg h4 {" + nl + i(l + 1) + "margin-top: 1.7777778em;" + nl + i(l + 1) + "margin-bottom: 0.4444444em;" + nl + i(l + 1) + "line-height: 1.5555556;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg img {" + nl + i(l + 1) + "margin-top: 1.7777778em;" + nl + i(l + 1) + "margin-bottom: 1.7777778em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg video {" + nl + i(l + 1) + "margin-top: 1.7777778em;" + nl + i(l + 1) + "margin-bottom: 1.7777778em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg figure {" + nl + i(l + 1) + "margin-top: 1.7777778em;" + nl + i(l + 1) + "margin-bottom: 1.7777778em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg figure > * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l + 1) + "margin-bottom: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg figure figcaption {" + nl + i(l + 1) + "font-size: 0.8888889em;" + nl + i(l + 1) + "line-height: 1.5;" + nl + i(l + 1) + "margin-top: 1em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg code {" + nl + i(l + 1) + "font-size: 0.8888889em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg h2 code {" + nl + i(l + 1) + "font-size: 0.8666667em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg h3 code {" + nl + i(l + 1) + "font-size: 0.875em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg pre {" + nl + i(l + 1) + "font-size: 0.8888889em;" + nl + i(l + 1) + "line-height: 1.75;" + nl + i(l + 1) + "margin-top: 2em;" + nl + i(l + 1) + "margin-bottom: 2em;" + nl + i(l + 1) + "border-radius: 0.375rem;" + nl + i(l + 1) + "padding-top: 1em;" + nl + i(l + 1) + "padding-right: 1.5em;" + nl + i(l + 1) + "padding-bottom: 1em;" + nl + i(l + 1) + "padding-left: 1.5em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg ol {" + nl + i(l + 1) + "margin-top: 1.3333333em;" + nl + i(l + 1) + "margin-bottom: 1.3333333em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg ul {" + nl + i(l + 1) + "margin-top: 1.3333333em;" + nl + i(l + 1) + "margin-bottom: 1.3333333em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg li {" + nl + i(l + 1) + "margin-top: 0.6666667em;" + nl + i(l + 1) + "margin-bottom: 0.6666667em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg ol > li {" + nl + i(l + 1) + "padding-left: 1.6666667em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg ol > li:before {" + nl + i(l + 1) + "left: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg ul > li {" + nl + i(l + 1) + "padding-left: 1.6666667em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg ul > li::before {" + nl + i(l + 1) + "width: 0.3333333em;" + nl + i(l + 1) + "height: 0.3333333em;" + nl + i(l + 1) + "top: calc(0.8888889em - 0.1666667em);" + nl + i(l + 1) + "left: 0.2222222em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg > ul > li p {" + nl + i(l + 1) + "margin-top: 0.8888889em;" + nl + i(l + 1) + "margin-bottom: 0.8888889em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg > ul > li > :first-child {" + nl + i(l + 1) + "margin-top: 1.3333333em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg > ul > li > :last-child {" + nl + i(l + 1) + "margin-bottom: 1.3333333em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg > ol > li > :first-child {" + nl + i(l + 1) + "margin-top: 1.3333333em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg > ol > li > :last-child {" + nl + i(l + 1) + "margin-bottom: 1.3333333em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg ol ol," + nl + i(l) + bp + "prose-lg ol ul," + nl + i(l) + bp + "prose-lg ul ol," + nl + i(l) + bp + "prose-lg ul ul {" + nl + i(l + 1) + "margin-top: 0.8888889em;" + nl + i(l + 1) + "margin-bottom: 0.8888889em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg hr {" + nl + i(l + 1) + "margin-top: 3.1111111em;" + nl + i(l + 1) + "margin-bottom: 3.1111111em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg hr + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg h2 + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg h3 + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg h4 + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg table {" + nl + i(l + 1) + "font-size: 0.8888889em;" + nl + i(l + 1) + "line-height: 1.5;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg thead th {" + nl + i(l + 1) + "padding-right: 0.75em;" + nl + i(l + 1) + "padding-bottom: 0.75em;" + nl + i(l + 1) + "padding-left: 0.75em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg thead th:first-child {" + nl + i(l + 1) + "padding-left: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg thead th:last-child {" + nl + i(l + 1) + "padding-right: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg tbody td {" + nl + i(l + 1) + "padding-top: 0.75em;" + nl + i(l + 1) + "padding-right: 0.75em;" + nl + i(l + 1) + "padding-bottom: 0.75em;" + nl + i(l + 1) + "padding-left: 0.75em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg tbody td:first-child {" + nl + i(l + 1) + "padding-left: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg tbody td:last-child {" + nl + i(l + 1) + "padding-right: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg > :first-child {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-lg > :last-child {" + nl + i(l + 1) + "margin-bottom: 0;" + nl + i(l) + "}" + nl; }; proseTypes.set("prose-lg", proseLg); // deno-lint-ignore ban-types const proseXl = (l: number, i: Function, nl: Function, bp: string): string => { return i(l) + bp + "prose-xl {" + nl + i(l + 1) + "font-size: 1.25rem;" + nl + i(l + 1) + "line-height: 1.8;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl p {" + nl + i(l + 1) + "margin-top: 1.2em;" + nl + i(l + 1) + "margin-bottom: 1.2em;" + nl + i(l) + "}" + nl + i(l) + bp + 'prose-xl [class~="lead"] {' + nl + i(l + 1) + "font-size: 1.2em;" + nl + i(l + 1) + "line-height: 1.5;" + nl + i(l + 1) + "margin-top: 1em;" + nl + i(l + 1) + "margin-bottom: 1em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl blockquote {" + nl + i(l + 1) + "margin-top: 1.6em;" + nl + i(l + 1) + "margin-bottom: 1.6em;" + nl + i(l + 1) + "padding-left: 1.0666667em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl h1 {" + nl + i(l + 1) + "font-size: 2.8em;" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l + 1) + "margin-bottom: 0.8571429em;" + nl + i(l + 1) + "line-height: 1;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl h2 {" + nl + i(l + 1) + "font-size: 1.8em;" + nl + i(l + 1) + "margin-top: 1.5555556em;" + nl + i(l + 1) + "margin-bottom: 0.8888889em;" + nl + i(l + 1) + "line-height: 1.1111111;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl h3 {" + nl + i(l + 1) + "font-size: 1.5em;" + nl + i(l + 1) + "margin-top: 1.6em;" + nl + i(l + 1) + "margin-bottom: 0.6666667em;" + nl + i(l + 1) + "line-height: 1.3333333;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl h4 {" + nl + i(l + 1) + "margin-top: 1.8em;" + nl + i(l + 1) + "margin-bottom: 0.6em;" + nl + i(l + 1) + "line-height: 1.6;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl img {" + nl + i(l + 1) + "margin-top: 2em;" + nl + i(l + 1) + "margin-bottom: 2em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl video {" + nl + i(l + 1) + "margin-top: 2em;" + nl + i(l + 1) + "margin-bottom: 2em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl figure {" + nl + i(l + 1) + "margin-top: 2em;" + nl + i(l + 1) + "margin-bottom: 2em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl figure > * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l + 1) + "margin-bottom: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl figure figcaption {" + nl + i(l + 1) + "font-size: 0.9em;" + nl + i(l + 1) + "line-height: 1.5555556;" + nl + i(l + 1) + "margin-top: 1em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl code {" + nl + i(l + 1) + "font-size: 0.9em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl h2 code {" + nl + i(l + 1) + "font-size: 0.8611111em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl h3 code {" + nl + i(l + 1) + "font-size: 0.9em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl pre {" + nl + i(l + 1) + "font-size: 0.9em;" + nl + i(l + 1) + "line-height: 1.7777778;" + nl + i(l + 1) + "margin-top: 2em;" + nl + i(l + 1) + "margin-bottom: 2em;" + nl + i(l + 1) + "border-radius: 0.5rem;" + nl + i(l + 1) + "padding-top: 1.1111111em;" + nl + i(l + 1) + "padding-right: 1.3333333em;" + nl + i(l + 1) + "padding-bottom: 1.1111111em;" + nl + i(l + 1) + "padding-left: 1.3333333em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl ol {" + nl + i(l + 1) + "margin-top: 1.2em;" + nl + i(l + 1) + "margin-bottom: 1.2em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl ul {" + nl + i(l + 1) + "margin-top: 1.2em;" + nl + i(l + 1) + "margin-bottom: 1.2em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl li {" + nl + i(l + 1) + "margin-top: 0.6em;" + nl + i(l + 1) + "margin-bottom: 0.6em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl ol > li {" + nl + i(l + 1) + "padding-left: 1.8em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl ol > li:before {" + nl + i(l + 1) + "left: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl ul > li {" + nl + i(l + 1) + "padding-left: 1.8em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl ul > li::before {" + nl + i(l + 1) + "width: 0.35em;" + nl + i(l + 1) + "height: 0.35em;" + nl + i(l + 1) + "top: calc(0.9em - 0.175em);" + nl + i(l + 1) + "left: 0.25em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl > ul > li p {" + nl + i(l + 1) + "margin-top: 0.8em;" + nl + i(l + 1) + "margin-bottom: 0.8em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl > ul > li > :first-child {" + nl + i(l + 1) + "margin-top: 1.2em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl > ul > li > :last-child {" + nl + i(l + 1) + "margin-bottom: 1.2em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl > ol > li > :first-child {" + nl + i(l + 1) + "margin-top: 1.2em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl > ol > li > :last-child {" + nl + i(l + 1) + "margin-bottom: 1.2em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl ol ol," + nl + i(l) + bp + "prose-xl ol ul," + nl + i(l) + bp + "prose-xl ul ol," + nl + i(l) + bp + "prose-xl ul ul {" + nl + i(l + 1) + "margin-top: 0.8em;" + nl + i(l + 1) + "margin-bottom: 0.8em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl hr {" + nl + i(l + 1) + "margin-top: 2.8em;" + nl + i(l + 1) + "margin-bottom: 2.8em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl hr + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl h2 + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl h3 + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl h4 + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl table {" + nl + i(l + 1) + "font-size: 0.9em;" + nl + i(l + 1) + "line-height: 1.5555556;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl thead th {" + nl + i(l + 1) + "padding-right: 0.6666667em;" + nl + i(l + 1) + "padding-bottom: 0.8888889em;" + nl + i(l + 1) + "padding-left: 0.6666667em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl thead th:first-child {" + nl + i(l + 1) + "padding-left: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl thead th:last-child {" + nl + i(l + 1) + "padding-right: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl tbody td {" + nl + i(l + 1) + "padding-top: 0.8888889em;" + nl + i(l + 1) + "padding-right: 0.6666667em;" + nl + i(l + 1) + "padding-bottom: 0.8888889em;" + nl + i(l + 1) + "padding-left: 0.6666667em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl tbody td:first-child {" + nl + i(l + 1) + "padding-left: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl tbody td:last-child {" + nl + i(l + 1) + "padding-right: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl > :first-child {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-xl > :last-child {" + nl + i(l + 1) + "margin-bottom: 0;" + nl + i(l) + "}" + nl; }; proseTypes.set("prose-xl", proseXl); // deno-lint-ignore ban-types const prose2xl = (l: number, i: Function, nl: Function, bp: string): string => { return i(l) + bp + "prose-2xl {" + nl + i(l + 1) + "font-size: 1.5rem;" + nl + i(l + 1) + "line-height: 1.6666667;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl p {" + nl + i(l + 1) + "margin-top: 1.3333333em;" + nl + i(l + 1) + "margin-bottom: 1.3333333em;" + nl + i(l) + "}" + nl + i(l) + bp + 'prose-2xl [class~="lead"] {' + nl + i(l + 1) + "font-size: 1.25em;" + nl + i(l + 1) + "line-height: 1.4666667;" + nl + i(l + 1) + "margin-top: 1.0666667em;" + nl + i(l + 1) + "margin-bottom: 1.0666667em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl blockquote {" + nl + i(l + 1) + "margin-top: 1.7777778em;" + nl + i(l + 1) + "margin-bottom: 1.7777778em;" + nl + i(l + 1) + "padding-left: 1.1111111em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl h1 {" + nl + i(l + 1) + "font-size: 2.6666667em;" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l + 1) + "margin-bottom: 0.875em;" + nl + i(l + 1) + "line-height: 1;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl h2 {" + nl + i(l + 1) + "font-size: 2em;" + nl + i(l + 1) + "margin-top: 1.5em;" + nl + i(l + 1) + "margin-bottom: 0.8333333em;" + nl + i(l + 1) + "line-height: 1.0833333;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl h3 {" + nl + i(l + 1) + "font-size: 1.5em;" + nl + i(l + 1) + "margin-top: 1.5555556em;" + nl + i(l + 1) + "margin-bottom: 0.6666667em;" + nl + i(l + 1) + "line-height: 1.2222222;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl h4 {" + nl + i(l + 1) + "margin-top: 1.6666667em;" + nl + i(l + 1) + "margin-bottom: 0.6666667em;" + nl + i(l + 1) + "line-height: 1.5;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl img {" + nl + i(l + 1) + "margin-top: 2em;" + nl + i(l + 1) + "margin-bottom: 2em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl video {" + nl + i(l + 1) + "margin-top: 2em;" + nl + i(l + 1) + "margin-bottom: 2em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl figure {" + nl + i(l + 1) + "margin-top: 2em;" + nl + i(l + 1) + "margin-bottom: 2em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl figure > * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l + 1) + "margin-bottom: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl figure figcaption {" + nl + i(l + 1) + "font-size: 0.8333333em;" + nl + i(l + 1) + "line-height: 1.6;" + nl + i(l + 1) + "margin-top: 1em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl code {" + nl + i(l + 1) + "font-size: 0.8333333em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl h2 code {" + nl + i(l + 1) + "font-size: 0.875em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl h3 code {" + nl + i(l + 1) + "font-size: 0.8888889em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl pre {" + nl + i(l + 1) + "font-size: 0.8333333em;" + nl + i(l + 1) + "line-height: 1.8;" + nl + i(l + 1) + "margin-top: 2em;" + nl + i(l + 1) + "margin-bottom: 2em;" + nl + i(l + 1) + "border-radius: 0.5rem;" + nl + i(l + 1) + "padding-top: 1.2em;" + nl + i(l + 1) + "padding-right: 1.6em;" + nl + i(l + 1) + "padding-bottom: 1.2em;" + nl + i(l + 1) + "padding-left: 1.6em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl ol {" + nl + i(l + 1) + "margin-top: 1.3333333em;" + nl + i(l + 1) + "margin-bottom: 1.3333333em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl ul {" + nl + i(l + 1) + "margin-top: 1.3333333em;" + nl + i(l + 1) + "margin-bottom: 1.3333333em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl li {" + nl + i(l + 1) + "margin-top: 0.5em;" + nl + i(l + 1) + "margin-bottom: 0.5em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl ol > li {" + nl + i(l + 1) + "padding-left: 1.6666667em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl ol > li:before {" + nl + i(l + 1) + "left: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl ul > li {" + nl + i(l + 1) + "padding-left: 1.6666667em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl ul > li::before {" + nl + i(l + 1) + "width: 0.3333333em;" + nl + i(l + 1) + "height: 0.3333333em;" + nl + i(l + 1) + "top: calc(0.8333333em - 0.1666667em);" + nl + i(l + 1) + "left: 0.25em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl > ul > li p {" + nl + i(l + 1) + "margin-top: 0.8333333em;" + nl + i(l + 1) + "margin-bottom: 0.8333333em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl > ul > li > :first-child {" + nl + i(l + 1) + "margin-top: 1.3333333em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl > ul > li > :last-child {" + nl + i(l + 1) + "margin-bottom: 1.3333333em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl > ol > li > :first-child {" + nl + i(l + 1) + "margin-top: 1.3333333em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl > ol > li > :last-child {" + nl + i(l + 1) + "margin-bottom: 1.3333333em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl ol ol," + nl + i(l) + bp + "prose-2xl ol ul," + nl + i(l) + bp + "prose-2xl ul ol," + nl + i(l) + bp + "prose-2xl ul ul {" + nl + i(l + 1) + "margin-top: 0.6666667em;" + nl + i(l + 1) + "margin-bottom: 0.6666667em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl hr {" + nl + i(l + 1) + "margin-top: 3em;" + nl + i(l + 1) + "margin-bottom: 3em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl hr + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl h2 + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl h3 + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl h4 + * {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl table {" + nl + i(l + 1) + "font-size: 0.8333333em;" + nl + i(l + 1) + "line-height: 1.4;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl thead th {" + nl + i(l + 1) + "padding-right: 0.6em;" + nl + i(l + 1) + "padding-bottom: 0.8em;" + nl + i(l + 1) + "padding-left: 0.6em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl thead th:first-child {" + nl + i(l + 1) + "padding-left: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl thead th:last-child {" + nl + i(l + 1) + "padding-right: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl tbody td {" + nl + i(l + 1) + "padding-top: 0.8em;" + nl + i(l + 1) + "padding-right: 0.6em;" + nl + i(l + 1) + "padding-bottom: 0.8em;" + nl + i(l + 1) + "padding-left: 0.6em;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl tbody td:first-child {" + nl + i(l + 1) + "padding-left: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl tbody td:last-child {" + nl + i(l + 1) + "padding-right: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl > :first-child {" + nl + i(l + 1) + "margin-top: 0;" + nl + i(l) + "}" + nl + i(l) + bp + "prose-2xl > :last-child {" + nl + i(l + 1) + "margin-bottom: 0;" + nl + i(l) + "}" + nl; }; proseTypes.set("prose-2xl", prose2xl); export default (identifier: string, level = 0, b = "", m = false) => { const i = indentFormatter(m); const nl = newlineFormatter(m)(); const bp = breakpointFormatter(b); if (proseTypes.has(identifier)) { return proseTypes.get(identifier)(level, i, nl, bp); } return; };"# ); to!(bin_01, "a!!!! + b!!!!!! + c!!!!!"); test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), tr, deno_7413_1, " import { a } from './foo'; import { Type } from './types'; " ); test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), tr, deno_7413_2, " import './foo'; " ); test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |t| { tr_config( t, Some(typescript::Config { no_empty_export: true, import_not_used_as_values: ImportsNotUsedAsValues::Preserve, ..Default::default() }), None, true, ) }, deno_7413_3, " import { a } from './foo'; import { Type } from './types'; " ); test!( Syntax::Typescript(TsSyntax { tsx: true, ..Default::default() }), |t| tsxr(t), imports_not_used_as_values_jsx_prag, r#"/** @jsx h */ import html, { h } from "example"; serve((_req) => html({ body: <div>Hello World!</div>, }) ); "# ); test!( Syntax::Typescript(TsSyntax { tsx: true, ..Default::default() }), |t| tsxr(t), imports_not_used_as_values_shebang_jsx_prag, r#"#!/usr/bin/env -S deno run -A /** @jsx h */ import html, { h } from "example"; serve((_req) => html({ body: <div>Hello World!</div>, }) ); "# ); test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), tr, issue_1124, " import { Type } from './types'; export type { Type }; " ); test!( Syntax::Typescript(Default::default()), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); let config = typescript::Config { no_empty_export: true, ..Default::default() }; ( resolver(unresolved_mark, top_level_mark, true), typescript(config, unresolved_mark, top_level_mark), async_to_generator(Default::default(), unresolved_mark), ) }, issue_1235_1, " class Service { async is(a: string): Promise<boolean> { return a.toUpperCase() === a; } } (async() => { await (new Service()).is('ABC'); })(); " ); test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |_| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); let config = typescript::Config { no_empty_export: true, ..Default::default() }; ( Optional::new(decorators(Default::default()), false), resolver(unresolved_mark, top_level_mark, true), typescript(config, unresolved_mark, top_level_mark), optional_chaining(Default::default(), unresolved_mark), ) }, issue_1149_1, " const tmp = tt?.map((t: any) => t).join((v: any) => v); " ); test!( Syntax::Typescript(Default::default()), |t| (tr(t), nullish_coalescing(Default::default())), issue_1123_1, r#" interface SuperSubmission { [key: string]: any; } const normalizedQuestionSet: any = {}; const submissions: SuperSubmission[] = ( normalizedQuestionSet.submissionIds ?? [] ).map( (id, index): SuperSubmission => { const submission = normalizedQuestionSet.submissions?.[id]; const submissionAnswers = (submission.answers ?? []).map( (answerId) => normalizedQuestionSet.answers?.[answerId] ); console.log(id, index); return { type: "super-submission", }; } ); console.log(submissions); "# ); // compile_to_class_constructor_collision_ignores_types test!( Syntax::Typescript(Default::default()), |t| tr_config( t, Some(typescript::Config { no_empty_export: true, ..Default::default() }), None, true ), compile_to_class_constructor_collision_ignores_types, r#" class C { // Output should not use `_initialiseProps` x: T; y = 0; constructor(T) {} } "# ); test!( Syntax::Typescript(TsSyntax { decorators: true, ..Default::default() }), |t| tr_config(t, None, Some(Default::default()), false), issue_367, " // before import { bind } from 'some'; class A { @bind public get foo() { return 1; } @bind public bar() { return 1; } }" ); to!( deno_8978, " import { any } from './dep.ts'; export { any }; export type { any as t }; " ); to!( deno_9097, " export namespace util { export type AssertEqual<T, Expected> = T extends Expected ? Expected extends T ? true : false : false; export function assertNever(_x: never): never { throw new Error(); } export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; export type OmitKeys<T, K extends string> = Pick<T, Exclude<keyof T, K>>; export type MakePartial<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>; export const arrayToEnum = <T extends string, U extends [T, ...T[]]>( items: U ): { [k in U[number]]: k } => { }; export const getValidEnumValues = (obj: any) => { }; export const getValues = (obj: any) => { }; export const objectValues = (obj: any) => { }; } " ); to!( namespace_001, " export namespace util { const c = 3; export const [a, b] = [1, 2, 3]; } " ); to!( namespace_002, " export namespace util { const c = 3; export function foo() { } function bar() { } } " ); to!( namespace_003, " namespace Test.Inner { export const c = 3; } namespace Test.Other { export interface Test {} } " ); to!( namespace_004, " namespace MyNamespace { export enum MyEnum { A = 1 } export namespace MyInnerNamespace { export enum MyEnum { A = 1 } } } namespace MyNamespace { export enum MyEnum { B = 1 } export namespace MyInnerNamespace { export const Dec2 = 2; } } namespace MyNamespace { enum MyEnum { A = 2 } } " ); to!( namespace_005, " namespace A { export class Test {} } namespace B { export import a = A; console.log(a.Test); import b = A; console.log(b.Test); } " ); to!( issue_1329, " namespace Test { export enum DummyValues { A = 'A', B = 'B', } } console(Test.DummyValues.A); " ); to!( deno_9289_1, " export class TestClass { public testMethod (args: TestClass.TestArgs) { return args.param1; } } declare namespace TestClass { export interface TestArgs { param1: boolean; } } " ); to!( deno_9289_2, " declare namespace TestClass { export interface TestArgs { param1: boolean; } } " ); to!( issue_1383, " declare global { const process: Process; } export {} " ); test_with_config!( issue_1472_1_define, typescript::Config { no_empty_export: true, ..Default::default() }, " class A extends Object { a = 1; constructor(public b = 2) { super(); } } " ); test_with_config!( issue_1472_1_no_define, typescript::Config { no_empty_export: true, ..Default::default() }, SET, " class A extends Object { a = 1; constructor(public b = 2) { super(); } } " ); to!( issue_1497_1, " class A { [(console.log(1), 'a')] = 1; static [(console.log(2), 'b')] = 2; } " ); to!( issue_1497_2, " class A { [(console.log(1), 'a')] = 1; static [(console.log(2), 'b')] = 2; [(console.log(3), 'c')]() {} } " ); to!( issue_1515_1, " export class A {} export namespace A { export class B extends A {} } " ); to!( issue_1515_2, " export namespace A { export class B extends A {} } export enum A {} " ); to!( issue_1515_3, " export class A {} export enum A {} " ); to!( class_expression_sequence, " const A = class { static a = 1; } " ); to!( issue_1508_1, " declare namespace twttr { export const txt: typeof import('twitter-text') } " ); to!( issue_1517_1, " interface X { get foo(): string; set foo(v: string | number); } " ); to!( issue_1517_2, " type Y = { get bar(): string; set bar(v: string | number); } " ); to!( import_shadow_named, " import { Test } from 'test'; const Test = 2; console.log(Test); " ); to!( import_shadow_default, " import Test from 'test'; const Test = 2; console.log(Test); " ); to!( import_shadow_namespace, " import * as Test from 'test'; const Test = 2; console.log(Test); " ); to!( import_shadow_array_pat, " import { Test } from 'test'; const [Test] = []; console.log(a); " ); to!( import_shadow_array_pat_default, " import { Test } from 'test'; const [a = Test] = []; console.log(a); " ); to!( import_shadow_object_pat, " import { Test } from 'test'; const {Test: a} = {}; console.log(a); " ); to!( import_shadow_object_pat_default, " import { Test } from 'test'; const {a = Test} = {}; console.log(Test); " ); to!( import_shadow_type, " import { Test } from 'test'; interface Test {} " ); to!( import_concrete, " import { Test } from 'test'; console.log(Test); " ); to!( import_shadow_type_concrete, " import { Test } from 'test'; interface Test {} console.log(Test); " ); to!( import_hoist, " console.log(Test); import { Test } from 'test'; " ); // to!( import_shadow_hoist, " const Test = 2; console.log(Test); import { Test } from 'test'; " ); to!( import_shadow_hoist_type, " interface Test {} import { Test } from 'test'; " ); to!( import_shadow_hoist_type_concrete, " interface Test {} console.log(Test); import { Test } from 'test'; " ); to!( issue_1448_1, " import F = require('yaml') console.log(F) " ); to!( constructor_1, "export class Query { public text: string; public args: EncodedArg[]; public fields?: string[]; constructor(config: QueryObjectConfig); constructor(text: string, ...args: unknown[]); }" ); to!( constructor_2, "export class Context { app!: Application; request!: ServerRequest; url!: URL; response: Response & { headers: Headers } = { headers: new Headers() }; params: Record<string, string> = {}; customContext: any; #store?: Map<string | symbol, unknown>; #body: Promise<unknown> | undefined; constructor(opts: ContextOptions); constructor(c: Context); constructor(optionsOrContext: ContextOptions | Context) { if (optionsOrContext instanceof Context) { Object.assign(this, optionsOrContext); this.customContext = this; return; } } }" ); to!( issue_1593, " export = 'something'; " ); to!( deno_10462, " import { foo } from './temp2.ts'; const _: foo = null; console.log({ foo: 1 }); " ); to!( pr_1835, r#" import { A } from "./a"; import { B } from "./b"; import { C } from "./c"; const { A: AB } = B; const { CB = C } = B; console.log(A, AB, CB); "# ); to!( deno_10684, " import { Foo } from './temp2.ts'; const a: Foo = null; console.log(a); const b = { Foo: 1 }; console.log(b.Foo) " ); to!( issue_1869_3, " var _class; let TestClass = _class = someClassDecorator((_class = class TestClass { static Something = 'hello'; static SomeProperties = { firstProp: TestClass.Something }; }) || _class) || _class; function someClassDecorator(c) { return c; } " ); to!( issue_2219, " import type { TestInfo } from './config' export { TestInfo } " ); to!( issue_3827, " import { foo } from './foo' type A = { get [foo](): number } " ); to!( issue_1122_2, " const identifier = 'bar'; class Foo { identifier = 5; } " ); to!( issue_1122_5, " const identifier = 'bar'; class Foo { static identifier = 5; } " ); to!( deno_12395_import_equals_1, " import * as mongo from 'https://deno.land/x/mongo@v0.27.0/mod.ts'; import MongoClient = mongo.MongoClient; const mongoClient = new MongoClient(); " ); to!( deno_12395_import_equals_2, " import * as mongo from 'https://deno.land/x/mongo@v0.27.0/mod.ts'; import MongoClient = mongo.MongoClient; const mongoClient: MongoClient = {}; " ); test_with_config!( deno_12532_declare_class_prop, typescript::Config { no_empty_export: true, ..Default::default() }, " export class Foo { x: number; constructor(x: number) { this.x = x; } } export class Bar extends Foo { declare x: 123; constructor() { super(123); } } " ); to!( issue_2613, " export = function (foo: string, bar: number): boolean { return true }; " ); to!( issue_2809, "enum Color { Aqua = '#00ffff', Cyan = Aqua, }" ); to!( issue_2886_enum_namespace_block_scoping, " export enum Enum { test = 1 } namespace Namespace { export enum Enum { test = 1 } export enum Enum { test2 = 1 } } { enum Enum { test = 1 } namespace Namespace { export enum Enum { test = 1 } } } { enum Enum { test = 1 } namespace Namespace { export enum Enum { test = 1 } } } " ); #[testing::fixture("tests/fixture/**/input.ts")] #[testing::fixture("tests/fixture/**/input.tsx")] fn exec(input: PathBuf) { let output = input.with_file_name("output.js"); test_fixture( Syntax::Typescript(TsSyntax { tsx: input.to_string_lossy().ends_with(".tsx"), ..Default::default() }), &|t| (tr(t), properties(t, true)), &input, &output, Default::default(), ); } to!( parameter_properties_with_computed, " class A { [console.log(123)] = 456 constructor(public a = 1) {} } let b = class { [console.log(456)] = 123 constructor(public a = 1) {} } " ); test!( Syntax::Typescript(TsSyntax::default()), |t| tr_config(t, None, None, true), export_import_assign, r#" export import foo = require("foo"); foo(); "# ); test!( Syntax::Typescript(TsSyntax::default()), |t| tr_config( t, Some(typescript::Config { import_export_assign_config: TsImportExportAssignConfig::NodeNext, ..Default::default() }), None, true, ), node_next_1, r#" import foo = require("foo"); foo(); "# ); test!( Syntax::Typescript(TsSyntax::default()), |t| tr_config( t, Some(typescript::Config { import_export_assign_config: TsImportExportAssignConfig::NodeNext, ..Default::default() }), None, true ), node_next_2, r#" export import foo = require("foo"); foo(); "# ); test_with_config!( issue_6023, Default::default(), " abstract class Shape { abstract height: number; abstract width: number; } " ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, issue_6219, "enum A{ a=a, }" ); test!( ::swc_ecma_parser::Syntax::Typescript(Default::default()), tr, issue_7106, " export class test { #throw() {} #new() {} test() { this.#throw(); this.#new(); } } " ); test!( Syntax::Typescript(TsSyntax::default()), |t| tr_config( t, Some(typescript::Config { ts_enum_is_mutable: true, ..Default::default() }), None, true, ), ts_enum_is_mutable_true, r#" enum D { A, B = 2, } (D as any).A = 5; console.log(D.A); const enum E { A, B, } console.log(E.B); const enum F { A = 2, } enum G { A = F.A } console.log(G.A); enum H { A = 2, } const enum I { A = H.A } console.log(I.A); "# ); test!( Syntax::Typescript(TsSyntax::default()), |t| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); ( resolver(unresolved_mark, top_level_mark, false), tsx( t.cm.clone(), typescript::Config { verbatim_module_syntax: false, ..Default::default() }, TsxConfig::default(), t.comments.clone(), unresolved_mark, top_level_mark, ), ) }, ts_jsx_bad_pragma, r#"/** @jsx bad-pragma */"# );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_transforms_typescript/tests/strip_correctness.rs
Rust
use std::path::PathBuf; use swc_common::{FileName, Mark}; use swc_ecma_ast::*; use swc_ecma_codegen::to_code_default; use swc_ecma_parser::{lexer::Lexer, EsSyntax, Parser, Syntax, TsSyntax}; use swc_ecma_transforms_base::{fixer::fixer, hygiene::hygiene, resolver}; use swc_ecma_transforms_typescript::typescript; #[testing::fixture("../swc_ecma_parser/tests/tsc/**/*.ts")] #[testing::fixture("../swc_ecma_parser/tests/tsc/**/*.tsx")] #[testing::fixture("../swc_ecma_parser/tests/typescript/**/*.ts")] #[testing::fixture("../swc_ecma_parser/tests/typescript/**/*.tsx")] fn identity(entry: PathBuf) { let file_name = entry .to_string_lossy() .replace("\\\\", "/") .replace('\\', "/"); let ignored = &[ // Cannot run the test with current test suite "multilinex", // Stack size "stack-size", "issue-716", "parenthesizedTypes.ts", // These tests are hard to debug because file is large "emitCompoundExponentiationAssignmentWithIndexingOnLHS3.ts", "emitExponentiationOperator1.ts", "emitExponentiationOperator3.ts", "emitExponentiationOperator4.ts", "emitExponentiationOperatorInTempalteString4.ts", "emitExponentiationOperatorInTempalteString4ES6.ts", "exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts", // `let[0] = 'foo'` is useless "letIdentifierInElementAccess01.ts", // decorator "issue-2417", ]; // TODO: Unignore let postponed = &[ "decoratorOnClassMethod11.ts", "elementAccessChain.3.ts", "awaitUsingDeclarationsInForAwaitOf.ts", "awaitUsingDeclarationsInForOf.1.ts", "usingDeclarationsInForOf.1.ts", "usingDeclarationsInForAwaitOf.ts", "tsxReactEmitNesting.tsx", "staticAutoAccessorsWithDecorators.ts", "generatorTypeCheck59.ts", "generatorTypeCheck61.ts", "parserAssignmentExpression1.ts", "objectRestNegative.ts", "parserSuperExpression2.ts", "propertyAccessChain.3.ts", "esDecorators-classDeclaration-classSuper.2.ts", "esDecorators-classExpression-classSuper.2.ts", "contextualTypes.ts", "decoratorOnClassMethod12.ts", "decoratorExpression.2.ts", "preservesThis.ts", ]; // TODO: Unignore const enum test let ignore = file_name.contains("export-import-require") || file_name.contains("issue-866") || file_name.contains("jsdocTypeFromChainedAssignment3") || file_name.contains("enumConstantMembers") || postponed .iter() .any(|postponed| file_name.ends_with(postponed)) || ignored.iter().any(|ignored| file_name.contains(ignored)); if ignore { return; } ::testing::run_test(false, |cm, handler| -> Result<(), ()> { let src = cm.load_file(&entry).expect("failed to load file"); println!("{}", src.src); let mut parser: Parser<Lexer> = Parser::new( Syntax::Typescript(TsSyntax { tsx: file_name.contains("tsx"), decorators: true, dts: false, no_early_errors: false, disallow_ambiguous_jsx_like: false, }), (&*src).into(), None, ); let js_content = { // Parse source let program = parser .parse_typescript_module() .map(|p| { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); Program::Module(p) .apply(resolver(unresolved_mark, top_level_mark, true)) .apply(typescript( typescript::Config { no_empty_export: true, ..Default::default() }, unresolved_mark, top_level_mark, )) .apply(hygiene()) .apply(fixer(None)) }) .map_err(|e| { eprintln!("failed to parse as typescript module"); e.into_diagnostic(handler).emit(); }); // We are not testing parser issues let program = match program { Ok(program) => program, Err(_) => return Ok(()), }; to_code_default(cm.clone(), None, &program) }; println!("---------------- JS ----------------\n\n{}", js_content); let js_fm = cm.new_source_file(FileName::Anon.into(), js_content.clone()); let mut parser: Parser<Lexer> = Parser::new( Syntax::Es(EsSyntax { jsx: file_name.contains("tsx"), decorators: true, decorators_before_export: true, export_default_from: true, import_attributes: true, allow_super_outside_method: true, auto_accessors: true, ..Default::default() }), (&*js_fm).into(), None, ); // It's very unscientific. // TODO: Change this with visitor if js_content.contains("import") || js_content.contains("export") { parser .parse_module() .unwrap_or_else(|err| panic!("{} is invalid module\n{:?}", js_content, err)); } else { parser .parse_script() .unwrap_or_else(|err| panic!("{} is invalid script\n{:?}", js_content, err)); } Ok(()) }) .expect("failed to run test"); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_usage_analyzer/src/alias/ctx.rs
Rust
use std::ops::{Deref, DerefMut}; use super::InfectionCollector; impl InfectionCollector { pub(super) fn with_ctx(&mut self, ctx: Ctx) -> WithCtx { let orig_ctx = self.ctx; self.ctx = ctx; WithCtx { analyzer: self, orig_ctx, } } } #[derive(Debug, Default, Clone, Copy)] pub(crate) struct Ctx { pub track_expr_ident: bool, pub is_callee: bool, pub is_pat_decl: bool, } pub(super) struct WithCtx<'a> { analyzer: &'a mut InfectionCollector, orig_ctx: Ctx, } impl Deref for WithCtx<'_> { type Target = InfectionCollector; fn deref(&self) -> &Self::Target { self.analyzer } } impl DerefMut for WithCtx<'_> { fn deref_mut(&mut self) -> &mut Self::Target { self.analyzer } } impl Drop for WithCtx<'_> { fn drop(&mut self) { self.analyzer.ctx = self.orig_ctx; } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_usage_analyzer/src/alias/mod.rs
Rust
#![allow(clippy::needless_update)] use rustc_hash::FxHashSet; use swc_common::SyntaxContext; use swc_ecma_ast::*; use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; use self::ctx::Ctx; use crate::{marks::Marks, util::is_global_var_with_pure_property_access}; mod ctx; #[derive(Default)] #[non_exhaustive] pub struct AliasConfig { pub marks: Option<Marks>, pub ignore_nested: bool, /// TODO(kdy1): This field is used for sequential inliner. /// It should be renamed to some correct name. pub need_all: bool, /// We can skip visiting children nodes in some cases. /// /// Because we recurse in the usage analyzer, we don't need to recurse into /// child node that the usage analyzer will invoke [`collect_infects_from`] /// on. pub ignore_named_child_scope: bool, } impl AliasConfig { pub fn marks(mut self, arg: Option<Marks>) -> Self { self.marks = arg; self } pub fn ignore_nested(mut self, arg: bool) -> Self { self.ignore_nested = arg; self } pub fn ignore_named_child_scope(mut self, arg: bool) -> Self { self.ignore_named_child_scope = arg; self } pub fn need_all(mut self, arg: bool) -> Self { self.need_all = arg; self } } pub trait InfectableNode { fn is_fn_or_arrow_expr(&self) -> bool; } impl InfectableNode for Function { fn is_fn_or_arrow_expr(&self) -> bool { false } } impl InfectableNode for Expr { fn is_fn_or_arrow_expr(&self) -> bool { matches!(self, Expr::Arrow(..) | Expr::Fn(..)) } } impl<T> InfectableNode for Box<T> where T: InfectableNode, { fn is_fn_or_arrow_expr(&self) -> bool { (**self).is_fn_or_arrow_expr() } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum AccessKind { Reference, Call, } pub type Access = (Id, AccessKind); pub fn collect_infects_from<N>(node: &N, config: AliasConfig) -> FxHashSet<Access> where N: InfectableNode + VisitWith<InfectionCollector>, { if config.ignore_nested && node.is_fn_or_arrow_expr() { return Default::default(); } let unresolved_ctxt = config .marks .map(|m| SyntaxContext::empty().apply_mark(m.unresolved_mark)); let mut visitor = InfectionCollector { config, unresolved_ctxt, ctx: Ctx { track_expr_ident: true, ..Default::default() }, bindings: FxHashSet::default(), accesses: FxHashSet::default(), max_entries: None, }; node.visit_with(&mut visitor); visitor.accesses } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct TooManyAccesses; /// If the number of accesses exceeds `max_entries`, it returns `Err(())`. pub fn try_collect_infects_from<N>( node: &N, config: AliasConfig, max_entries: usize, ) -> Result<FxHashSet<Access>, TooManyAccesses> where N: InfectableNode + VisitWith<InfectionCollector>, { if config.ignore_nested && node.is_fn_or_arrow_expr() { return Ok(Default::default()); } let unresolved_ctxt = config .marks .map(|m| SyntaxContext::empty().apply_mark(m.unresolved_mark)); let mut visitor = InfectionCollector { config, unresolved_ctxt, ctx: Ctx { track_expr_ident: true, ..Default::default() }, bindings: FxHashSet::default(), accesses: FxHashSet::default(), max_entries: Some(max_entries), }; node.visit_with(&mut visitor); if visitor.accesses.len() > max_entries { return Err(TooManyAccesses); } Ok(visitor.accesses) } pub struct InfectionCollector { #[allow(unused)] config: AliasConfig, unresolved_ctxt: Option<SyntaxContext>, bindings: FxHashSet<Id>, ctx: Ctx, accesses: FxHashSet<Access>, max_entries: Option<usize>, } impl InfectionCollector { fn add_binding(&mut self, e: &Ident) { if self.bindings.insert(e.to_id()) { self.accesses.remove(&(e.to_id(), AccessKind::Reference)); self.accesses.remove(&(e.to_id(), AccessKind::Call)); } } fn add_usage(&mut self, e: Id) { if self.bindings.contains(&e) { return; } if self.unresolved_ctxt == Some(e.1) && is_global_var_with_pure_property_access(&e.0) { return; } self.accesses.insert(( e, if self.ctx.is_callee { AccessKind::Call } else { AccessKind::Reference }, )); } } impl Visit for InfectionCollector { noop_visit_type!(); fn visit_arrow_expr(&mut self, n: &ArrowExpr) { let old = self.ctx.is_pat_decl; for p in &n.params { self.ctx.is_pat_decl = true; p.visit_with(self); } n.body.visit_with(self); self.ctx.is_pat_decl = old; } fn visit_assign_expr(&mut self, n: &AssignExpr) { if self.config.ignore_named_child_scope && n.op == op!("=") && n.left.as_simple().and_then(|l| l.leftmost()).is_some() { n.left.visit_with(self); return; } n.visit_children_with(self); } fn visit_assign_pat_prop(&mut self, node: &AssignPatProp) { node.value.visit_with(self); if self.ctx.is_pat_decl { self.add_binding(&node.key.clone().into()); } } fn visit_bin_expr(&mut self, e: &BinExpr) { match e.op { op!("in") | op!("instanceof") | op!(bin, "-") | op!(bin, "+") | op!("/") | op!("*") | op!("%") | op!("&") | op!("^") | op!("|") | op!("==") | op!("===") | op!("!=") | op!("!==") | op!("<") | op!("<=") | op!(">") | op!(">=") | op!("<<") | op!(">>") | op!(">>>") => { let ctx = Ctx { track_expr_ident: false, is_callee: false, ..self.ctx }; e.visit_children_with(&mut *self.with_ctx(ctx)); } _ => { let ctx = Ctx { track_expr_ident: true, is_callee: false, ..self.ctx }; e.visit_children_with(&mut *self.with_ctx(ctx)); } } } fn visit_callee(&mut self, n: &Callee) { let ctx = Ctx { is_callee: true, ..self.ctx }; n.visit_children_with(&mut *self.with_ctx(ctx)); } fn visit_class_decl(&mut self, node: &ClassDecl) { self.add_binding(&node.ident); node.visit_children_with(self); } fn visit_cond_expr(&mut self, e: &CondExpr) { { let ctx = Ctx { track_expr_ident: false, is_callee: false, ..self.ctx }; e.test.visit_with(&mut *self.with_ctx(ctx)); } { let ctx = Ctx { track_expr_ident: true, ..self.ctx }; e.cons.visit_with(&mut *self.with_ctx(ctx)); e.alt.visit_with(&mut *self.with_ctx(ctx)); } } fn visit_expr(&mut self, e: &Expr) { if let Some(max_entries) = self.max_entries { if self.accesses.len() >= max_entries { return; } } match e { Expr::Ident(i) => { if self.ctx.track_expr_ident { self.add_usage(i.to_id()); } } _ => { let ctx = Ctx { track_expr_ident: true, is_pat_decl: false, ..self.ctx }; e.visit_children_with(&mut *self.with_ctx(ctx)); } } } fn visit_fn_decl(&mut self, n: &FnDecl) { self.add_binding(&n.ident); if self.config.ignore_named_child_scope { return; } n.visit_children_with(self); } fn visit_fn_expr(&mut self, n: &FnExpr) { if self.config.ignore_named_child_scope && n.ident.is_some() { return; } n.visit_children_with(self); } fn visit_function(&mut self, n: &Function) { if let Some(max_entries) = self.max_entries { if self.accesses.len() >= max_entries { return; } } n.visit_children_with(self); } fn visit_ident(&mut self, n: &Ident) { self.add_usage(n.to_id()); } fn visit_member_expr(&mut self, n: &MemberExpr) { { let ctx = Ctx { track_expr_ident: self.config.need_all, ..self.ctx }; n.obj.visit_with(&mut *self.with_ctx(ctx)); } { let ctx = Ctx { track_expr_ident: self.config.need_all, ..self.ctx }; n.prop.visit_with(&mut *self.with_ctx(ctx)); } } fn visit_member_prop(&mut self, n: &MemberProp) { if let MemberProp::Computed(c) = &n { c.visit_with(&mut *self.with_ctx(Ctx { is_callee: false, ..self.ctx })); } } fn visit_param(&mut self, node: &Param) { let old = self.ctx.is_pat_decl; self.ctx.is_pat_decl = true; node.visit_children_with(self); self.ctx.is_pat_decl = old; } fn visit_pat(&mut self, node: &Pat) { node.visit_children_with(self); if self.ctx.is_pat_decl { if let Pat::Ident(i) = node { self.add_binding(i) } } } fn visit_prop_name(&mut self, n: &PropName) { if let PropName::Computed(c) = &n { c.visit_with(&mut *self.with_ctx(Ctx { is_callee: false, ..self.ctx })); } } fn visit_stmt(&mut self, n: &Stmt) { if let Some(max_entries) = self.max_entries { if self.accesses.len() >= max_entries { return; } } n.visit_children_with(self); } fn visit_super_prop_expr(&mut self, n: &SuperPropExpr) { if let SuperProp::Computed(c) = &n.prop { c.visit_with(&mut *self.with_ctx(Ctx { is_callee: false, ..self.ctx })); } } fn visit_unary_expr(&mut self, e: &UnaryExpr) { match e.op { op!("~") | op!(unary, "-") | op!(unary, "+") | op!("!") | op!("typeof") | op!("void") => { let ctx = Ctx { track_expr_ident: false, is_callee: false, ..self.ctx }; e.visit_children_with(&mut *self.with_ctx(ctx)); } _ => { let ctx = Ctx { track_expr_ident: true, is_callee: false, ..self.ctx }; e.visit_children_with(&mut *self.with_ctx(ctx)); } } } fn visit_update_expr(&mut self, e: &UpdateExpr) { let ctx = Ctx { track_expr_ident: false, is_callee: false, ..self.ctx }; e.arg.visit_with(&mut *self.with_ctx(ctx)); } fn visit_var_declarator(&mut self, n: &VarDeclarator) { { let old = self.ctx.is_pat_decl; self.ctx.is_pat_decl = true; n.name.visit_with(self); self.ctx.is_pat_decl = old; } if self.config.ignore_named_child_scope { if let (Pat::Ident(..), Some(..)) = (&n.name, n.init.as_deref()) { return; } } { let old = self.ctx.is_pat_decl; self.ctx.is_pat_decl = false; n.init.visit_with(self); self.ctx.is_pat_decl = old; } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_usage_analyzer/src/analyzer/ctx.rs
Rust
#![allow(dead_code)] use std::ops::{Deref, DerefMut}; use swc_ecma_ast::VarDeclKind; use swc_ecma_utils::{Type, Value}; use super::{storage::Storage, UsageAnalyzer}; impl<S> UsageAnalyzer<S> where S: Storage, { pub(super) fn with_ctx(&mut self, ctx: Ctx) -> WithCtx<S> { let orig_ctx = self.ctx; self.ctx = ctx; WithCtx { analyzer: self, orig_ctx, } } } #[derive(Debug, Default, Clone, Copy)] #[non_exhaustive] pub struct Ctx { pub var_decl_kind_of_pat: Option<VarDeclKind>, pub in_decl_with_no_side_effect_for_member_access: bool, pub in_pat_of_var_decl: bool, pub in_pat_of_var_decl_with_init: Option<Value<Type>>, pub in_pat_of_param: bool, pub in_catch_param: bool, pub is_id_ref: bool, pub in_await_arg: bool, pub in_left_of_for_loop: bool, pub executed_multiple_time: bool, pub in_cond: bool, pub inline_prevented: bool, pub is_top_level: bool, } pub(super) struct WithCtx<'a, S> where S: Storage, { analyzer: &'a mut UsageAnalyzer<S>, orig_ctx: Ctx, } impl<S> Deref for WithCtx<'_, S> where S: Storage, { type Target = UsageAnalyzer<S>; fn deref(&self) -> &Self::Target { self.analyzer } } impl<S> DerefMut for WithCtx<'_, S> where S: Storage, { fn deref_mut(&mut self) -> &mut Self::Target { self.analyzer } } impl<S> Drop for WithCtx<'_, S> where S: Storage, { fn drop(&mut self) { self.analyzer.ctx = self.orig_ctx; } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_usage_analyzer/src/analyzer/mod.rs
Rust
use rustc_hash::FxHashMap; use swc_common::SyntaxContext; use swc_ecma_ast::*; use swc_ecma_utils::{ find_pat_ids, ident::IdentLike, ExprCtx, ExprExt, IsEmpty, StmtExt, Type, Value, }; use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; use swc_timer::timer; pub use self::ctx::Ctx; use self::storage::*; use crate::{ alias::{collect_infects_from, AliasConfig}, marks::Marks, util::can_end_conditionally, }; mod ctx; pub mod storage; /// TODO: Track assignments to variables via `arguments`. /// TODO: Scope-local. (Including block) /// /// If `marks` is [None], markers are ignored. pub fn analyze_with_storage<S, N>(n: &N, marks: Option<Marks>) -> S where S: Storage, N: VisitWith<UsageAnalyzer<S>>, { let _timer = timer!("analyze"); let mut v = UsageAnalyzer { data: Default::default(), marks, scope: Default::default(), ctx: Default::default(), expr_ctx: ExprCtx { unresolved_ctxt: SyntaxContext::empty() .apply_mark(marks.map(|m| m.unresolved_mark).unwrap_or_default()), is_unresolved_ref_safe: false, in_strict: false, remaining_depth: 3, }, used_recursively: FxHashMap::default(), }; n.visit_with(&mut v); let top_scope = v.scope; v.data.top_scope().merge(top_scope.clone(), false); v.data.scope(SyntaxContext::empty()).merge(top_scope, false); v.data } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ScopeKind { Fn, Block, } #[derive(Debug, Clone)] enum RecursiveUsage { FnOrClass, Var { can_ignore: bool }, } /// This assumes there are no two variable with same name and same span hygiene. #[derive(Debug)] pub struct UsageAnalyzer<S> where S: Storage, { data: S, marks: Option<Marks>, scope: S::ScopeData, ctx: Ctx, expr_ctx: ExprCtx, used_recursively: FxHashMap<Id, RecursiveUsage>, } impl<S> UsageAnalyzer<S> where S: Storage, { fn with_child<F, Ret>(&mut self, child_ctxt: SyntaxContext, kind: ScopeKind, op: F) -> Ret where F: FnOnce(&mut UsageAnalyzer<S>) -> Ret, { let mut child = UsageAnalyzer { data: Default::default(), marks: self.marks, ctx: Ctx { is_top_level: false, ..self.ctx }, expr_ctx: self.expr_ctx, scope: Default::default(), used_recursively: self.used_recursively.clone(), }; let ret = op(&mut child); { let child_scope = child.data.scope(child_ctxt); child_scope.merge(child.scope.clone(), false); } self.scope.merge(child.scope, true); self.data.merge(kind, child.data); ret } fn visit_pat_id(&mut self, i: &Ident) { let Ctx { in_left_of_for_loop, in_pat_of_param, in_pat_of_var_decl, .. } = self.ctx; if self.ctx.in_pat_of_var_decl || self.ctx.in_pat_of_param || self.ctx.in_catch_param { let v = self.declare_decl( i, self.ctx.in_pat_of_var_decl_with_init, self.ctx.var_decl_kind_of_pat, false, ); if in_pat_of_param { v.mark_declared_as_fn_param(); } if in_pat_of_var_decl && in_left_of_for_loop { v.mark_declared_as_for_init(); } } else { self.report_usage(i); } } fn report_usage(&mut self, i: &Ident) { if i.sym == "arguments" { self.scope.mark_used_arguments(); } let i = i.to_id(); if let Some(recr) = self.used_recursively.get(&i) { if let RecursiveUsage::Var { can_ignore: false } = recr { self.data.report_usage(self.ctx, i.clone()); self.data.var_or_default(i.clone()).mark_used_above_decl() } self.data.var_or_default(i.clone()).mark_used_recursively(); return; } self.data.report_usage(self.ctx, i) } fn report_assign_pat(&mut self, p: &Pat, is_read_modify: bool) { for id in find_pat_ids(p) { // It's hard to determined the type of pat assignment self.data .report_assign(self.ctx, id, is_read_modify, Value::Unknown) } if let Pat::Expr(e) = p { match &**e { Expr::Ident(i) => { self.data .report_assign(self.ctx, i.to_id(), is_read_modify, Value::Unknown) } _ => self.mark_mutation_if_member(e.as_member()), } } } fn report_assign_expr_if_ident(&mut self, e: Option<&Ident>, is_op: bool, ty: Value<Type>) { if let Some(i) = e { self.data.report_assign(self.ctx, i.to_id(), is_op, ty) } } fn declare_decl( &mut self, i: &Ident, init_type: Option<Value<Type>>, kind: Option<VarDeclKind>, is_fn_decl: bool, ) -> &mut S::VarData { self.scope.add_declared_symbol(i); let v = self.data.declare_decl(self.ctx, i, init_type, kind); if is_fn_decl { v.mark_declared_as_fn_decl(); } v } fn visit_in_cond<T: VisitWith<Self>>(&mut self, t: &T) { let cnt = self.data.get_initialized_cnt(); t.visit_with(self); self.data.truncate_initialized_cnt(cnt) } fn visit_children_in_cond<T: VisitWith<Self>>(&mut self, t: &T) { let cnt = self.data.get_initialized_cnt(); t.visit_children_with(self); self.data.truncate_initialized_cnt(cnt) } fn mark_mutation_if_member(&mut self, e: Option<&MemberExpr>) { if let Some(m) = e { for_each_id_ref_in_expr(&m.obj, &mut |id| { self.data.mark_property_mutation(id.to_id()) }); } } } impl<S> Visit for UsageAnalyzer<S> where S: Storage, { noop_visit_type!(); fn visit_array_lit(&mut self, n: &ArrayLit) { let ctx = Ctx { is_id_ref: true, ..self.ctx }; n.visit_children_with(&mut *self.with_ctx(ctx)); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_arrow_expr(&mut self, n: &ArrowExpr) { self.with_child(n.ctxt, ScopeKind::Fn, |child| { { let ctx = Ctx { in_pat_of_param: true, inline_prevented: true, ..child.ctx }; n.params.visit_with(&mut *child.with_ctx(ctx)); } match &*n.body { BlockStmtOrExpr::BlockStmt(body) => { body.visit_with(child); } BlockStmtOrExpr::Expr(body) => { body.visit_with(child); } } }) } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_assign_expr(&mut self, n: &AssignExpr) { let is_op_assign = n.op != op!("="); n.left.visit_with(self); let ctx = Ctx { // We mark bar in // // foo[i] = bar // // as `used_as_ref`. is_id_ref: matches!(n.op, op!("=") | op!("||=") | op!("&&=") | op!("??=")), ..self.ctx }; n.right.visit_with(&mut *self.with_ctx(ctx)); match &n.left { AssignTarget::Pat(p) => { for id in find_pat_ids(p) { self.data.report_assign( self.ctx, id, is_op_assign, n.right.get_type(self.expr_ctx), ) } } AssignTarget::Simple(e) => { self.report_assign_expr_if_ident( e.as_ident().map(Ident::from).as_ref(), is_op_assign, n.right.get_type(self.expr_ctx), ); self.mark_mutation_if_member(e.as_member()) } }; if n.op == op!("=") { let left = match &n.left { AssignTarget::Simple(left) => left.leftmost().as_deref().map(Ident::to_id), AssignTarget::Pat(..) => None, }; if let Some(left) = left { let mut v = None; for id in collect_infects_from( &n.right, AliasConfig { marks: self.marks, ignore_named_child_scope: true, ..Default::default() }, ) { if v.is_none() { v = Some(self.data.var_or_default(left.to_id())); } v.as_mut().unwrap().add_infects_to(id.clone()); } } } } fn visit_assign_pat(&mut self, p: &AssignPat) { p.left.visit_with(self); { let ctx = Ctx { in_pat_of_param: false, var_decl_kind_of_pat: None, ..self.ctx }; p.right.visit_with(&mut *self.with_ctx(ctx)) } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_await_expr(&mut self, n: &AwaitExpr) { let ctx = Ctx { in_await_arg: true, ..self.ctx }; n.visit_children_with(&mut *self.with_ctx(ctx)); } fn visit_bin_expr(&mut self, e: &BinExpr) { if e.op.may_short_circuit() { let ctx = Ctx { is_id_ref: true, ..self.ctx }; e.left.visit_with(&mut *self.with_ctx(ctx)); let ctx = Ctx { in_cond: true, is_id_ref: true, ..self.ctx }; self.with_ctx(ctx).visit_in_cond(&e.right); } else { if e.op == op!("in") { for_each_id_ref_in_expr(&e.right, &mut |obj| { let var = self.data.var_or_default(obj.to_id()); var.mark_used_as_ref(); match &*e.left { Expr::Lit(Lit::Str(prop)) if prop.value.parse::<f64>().is_err() => { var.add_accessed_property(prop.value.clone()); } _ => { var.mark_indexed_with_dynamic_key(); } } }) } let ctx = Ctx { is_id_ref: false, ..self.ctx }; e.visit_children_with(&mut *self.with_ctx(ctx)); } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_binding_ident(&mut self, n: &BindingIdent) { self.visit_pat_id(&Ident::from(n)); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_block_stmt(&mut self, n: &BlockStmt) { self.with_child(n.ctxt, ScopeKind::Block, |child| { n.visit_children_with(child); }); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_call_expr(&mut self, n: &CallExpr) { let inline_prevented = self.ctx.inline_prevented || self .marks .map(|marks| n.ctxt.has_mark(marks.noinline)) .unwrap_or_default(); { let ctx = Ctx { inline_prevented, ..self.ctx }; n.callee.visit_with(&mut *self.with_ctx(ctx)); } if let Callee::Expr(callee) = &n.callee { for_each_id_ref_in_expr(callee, &mut |i| { self.data.var_or_default(i.to_id()).mark_used_as_callee(); }); match &**callee { Expr::Fn(callee) => { for (idx, p) in callee.function.params.iter().enumerate() { if let Some(arg) = n.args.get(idx) { if arg.spread.is_some() { break; } if is_safe_to_access_prop(&arg.expr) { if let Pat::Ident(id) = &p.pat { self.data .var_or_default(id.to_id()) .mark_initialized_with_safe_value(); } } } } } Expr::Arrow(callee) => { for (idx, p) in callee.params.iter().enumerate() { if let Some(arg) = n.args.get(idx) { if arg.spread.is_some() { break; } if is_safe_to_access_prop(&arg.expr) { if let Pat::Ident(id) = &p { self.data .var_or_default(id.to_id()) .mark_initialized_with_safe_value(); } } } } } _ => {} } } { let ctx = Ctx { inline_prevented, is_id_ref: true, ..self.ctx }; n.args.visit_with(&mut *self.with_ctx(ctx)); let call_may_mutate = match &n.callee { Callee::Expr(e) => call_may_mutate(e, self.expr_ctx), _ => true, }; if call_may_mutate { for a in &n.args { for_each_id_ref_in_expr(&a.expr, &mut |id| { self.data.mark_property_mutation(id.to_id()); }); } } } for arg in &n.args { for_each_id_ref_in_expr(&arg.expr, &mut |arg| { self.data.var_or_default(arg.to_id()).mark_used_as_arg(); }) } if let Callee::Expr(callee) = &n.callee { match &**callee { Expr::Ident(Ident { sym, .. }) if *sym == *"eval" => { self.scope.mark_eval_called(); } Expr::Member(m) if !m.obj.is_ident() => { for_each_id_ref_in_expr(&m.obj, &mut |id| { self.data.var_or_default(id.to_id()).mark_used_as_ref() }) } _ => {} } } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_catch_clause(&mut self, n: &CatchClause) { { let ctx = Ctx { in_cond: true, in_catch_param: true, ..self.ctx }; n.param.visit_with(&mut *self.with_ctx(ctx)); } { let ctx = Ctx { in_cond: true, ..self.ctx }; self.with_ctx(ctx).visit_in_cond(&n.body); } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_class(&mut self, n: &Class) { n.decorators.visit_with(self); { let ctx = Ctx { inline_prevented: true, ..self.ctx }; n.super_class.visit_with(&mut *self.with_ctx(ctx)); } self.with_child(n.ctxt, ScopeKind::Fn, |child| n.body.visit_with(child)) } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_class_decl(&mut self, n: &ClassDecl) { self.declare_decl(&n.ident, Some(Value::Unknown), None, false); n.visit_children_with(self); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_class_expr(&mut self, n: &ClassExpr) { n.visit_children_with(self); if let Some(id) = &n.ident { self.declare_decl(id, Some(Value::Unknown), None, false); } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_class_method(&mut self, n: &ClassMethod) { n.function.decorators.visit_with(self); self.with_child(n.function.ctxt, ScopeKind::Fn, |a| { n.key.visit_with(a); { let ctx = Ctx { in_pat_of_param: true, ..a.ctx }; n.function.params.visit_with(&mut *a.with_ctx(ctx)); } n.function.visit_with(a); }); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_class_prop(&mut self, n: &ClassProp) { let ctx = Ctx { is_id_ref: true, ..self.ctx }; n.visit_children_with(&mut *self.with_ctx(ctx)); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_computed_prop_name(&mut self, n: &ComputedPropName) { let ctx = Ctx { is_id_ref: true, ..self.ctx }; n.visit_children_with(&mut *self.with_ctx(ctx)); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_cond_expr(&mut self, n: &CondExpr) { n.test.visit_with(self); { let ctx = Ctx { in_cond: true, ..self.ctx }; self.with_ctx(ctx).visit_in_cond(&n.cons); self.with_ctx(ctx).visit_in_cond(&n.alt); } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_constructor(&mut self, n: &Constructor) { self.with_child(n.ctxt, ScopeKind::Fn, |child| { { let ctx = Ctx { in_pat_of_param: true, ..child.ctx }; n.params.visit_with(&mut *child.with_ctx(ctx)); } // Bypass visit_block_stmt if let Some(body) = &n.body { body.visit_with(child); } }) } fn visit_default_decl(&mut self, d: &DefaultDecl) { d.visit_children_with(self); match d { DefaultDecl::Class(c) => { if let Some(i) = &c.ident { self.data.var_or_default(i.to_id()).prevent_inline(); } } DefaultDecl::Fn(f) => { if let Some(i) = &f.ident { self.data.var_or_default(i.to_id()).prevent_inline(); } } _ => {} } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_do_while_stmt(&mut self, n: &DoWhileStmt) { n.body.visit_with(&mut *self.with_ctx(Ctx { executed_multiple_time: true, ..self.ctx })); n.test.visit_with(&mut *self.with_ctx(Ctx { executed_multiple_time: true, ..self.ctx })); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_export_decl(&mut self, n: &ExportDecl) { n.visit_children_with(self); match &n.decl { Decl::Class(c) => { self.data.var_or_default(c.ident.to_id()).prevent_inline(); } Decl::Fn(f) => { self.data.var_or_default(f.ident.to_id()).prevent_inline(); } Decl::Var(v) => { let ids = find_pat_ids(v); for id in ids { self.data.var_or_default(id).mark_as_exported(); } } _ => {} } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_export_default_expr(&mut self, n: &ExportDefaultExpr) { let ctx = Ctx { is_id_ref: true, ..self.ctx }; n.visit_children_with(&mut *self.with_ctx(ctx)); } fn visit_export_named_specifier(&mut self, n: &ExportNamedSpecifier) { match &n.orig { ModuleExportName::Ident(orig) => { self.report_usage(orig); let v = self.data.var_or_default(orig.to_id()); v.prevent_inline(); v.mark_used_as_ref(); } ModuleExportName::Str(..) => {} }; } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip(self, e)))] fn visit_expr(&mut self, e: &Expr) { let ctx = Ctx { in_pat_of_var_decl: false, in_pat_of_param: false, in_catch_param: false, var_decl_kind_of_pat: None, in_pat_of_var_decl_with_init: None, ..self.ctx }; e.visit_children_with(&mut *self.with_ctx(ctx)); if let Expr::Ident(i) = e { #[cfg(feature = "tracing-spans")] { // debug!( // "Usage: `{}``; update = {:?}, assign_lhs = {:?} ", // i, // self.ctx.in_update_arg, // self.ctx.in_assign_lhs // ); } self.with_ctx(ctx).report_usage(i); } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_expr_or_spread(&mut self, e: &ExprOrSpread) { e.visit_children_with(self); if e.spread.is_some() { for_each_id_ref_in_expr(&e.expr, &mut |i| { self.data .var_or_default(i.to_id()) .mark_indexed_with_dynamic_key(); }); } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_fn_decl(&mut self, n: &FnDecl) { let ctx = Ctx { in_decl_with_no_side_effect_for_member_access: true, ..self.ctx }; self.with_ctx(ctx) .declare_decl(&n.ident, Some(Value::Known(Type::Obj)), None, true); if n.function.body.is_empty() { self.data.var_or_default(n.ident.to_id()).mark_as_pure_fn(); } let id = n.ident.to_id(); self.used_recursively .insert(id.clone(), RecursiveUsage::FnOrClass); n.visit_children_with(self); self.used_recursively.remove(&id); { let mut v = None; for id in collect_infects_from( &n.function, AliasConfig { marks: self.marks, ignore_named_child_scope: true, ..Default::default() }, ) { if v.is_none() { v = Some(self.data.var_or_default(n.ident.to_id())); } v.as_mut().unwrap().add_infects_to(id.clone()); } } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_fn_expr(&mut self, n: &FnExpr) { if let Some(n_id) = &n.ident { self.data .var_or_default(n_id.to_id()) .mark_declared_as_fn_expr(); self.used_recursively .insert(n_id.to_id(), RecursiveUsage::FnOrClass); n.visit_children_with(self); { let mut v = None; for id in collect_infects_from( &n.function, AliasConfig { marks: self.marks, ignore_named_child_scope: true, ..Default::default() }, ) { if v.is_none() { v = Some(self.data.var_or_default(n_id.to_id())); } v.as_mut().unwrap().add_infects_to(id); } } self.used_recursively.remove(&n_id.to_id()); } else { n.visit_children_with(self); } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_for_in_stmt(&mut self, n: &ForInStmt) { n.right.visit_with(self); self.with_child(SyntaxContext::empty(), ScopeKind::Block, |child| { let head_ctx = Ctx { in_left_of_for_loop: true, is_id_ref: true, executed_multiple_time: true, in_cond: true, ..child.ctx }; n.left.visit_with(&mut *child.with_ctx(head_ctx)); n.right.visit_with(child); if let ForHead::Pat(pat) = &n.left { child.with_ctx(head_ctx).report_assign_pat(pat, true) } let ctx = Ctx { executed_multiple_time: true, in_cond: true, ..child.ctx }; child.with_ctx(ctx).visit_in_cond(&n.body); }); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_for_of_stmt(&mut self, n: &ForOfStmt) { n.right.visit_with(self); self.with_child(SyntaxContext::empty(), ScopeKind::Block, |child| { let head_ctx = Ctx { in_left_of_for_loop: true, is_id_ref: true, executed_multiple_time: true, in_cond: true, ..child.ctx }; n.left.visit_with(&mut *child.with_ctx(head_ctx)); if let ForHead::Pat(pat) = &n.left { child.with_ctx(head_ctx).report_assign_pat(pat, true) } let ctx = Ctx { executed_multiple_time: true, in_cond: true, ..child.ctx }; child.with_ctx(ctx).visit_in_cond(&n.body); }); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_for_stmt(&mut self, n: &ForStmt) { n.init.visit_with(self); let ctx = Ctx { executed_multiple_time: true, in_cond: true, ..self.ctx }; self.with_ctx(ctx).visit_in_cond(&n.test); self.with_ctx(ctx).visit_in_cond(&n.update); self.with_ctx(ctx).visit_in_cond(&n.body); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_function(&mut self, n: &Function) { n.decorators.visit_with(self); let ctx = Ctx { ..self.ctx }; self.with_ctx(ctx) .with_child(n.ctxt, ScopeKind::Fn, |child| { n.params.visit_with(child); if let Some(body) = &n.body { // We use visit_children_with instead of visit_with to bypass block scope // handler. body.visit_children_with(child); } }) } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_getter_prop(&mut self, n: &GetterProp) { self.with_child(SyntaxContext::empty(), ScopeKind::Fn, |a| { n.key.visit_with(a); n.body.visit_with(a); }); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_if_stmt(&mut self, n: &IfStmt) { let ctx = Ctx { in_cond: true, ..self.ctx }; n.test.visit_with(self); self.with_ctx(ctx).visit_in_cond(&n.cons); self.with_ctx(ctx).visit_in_cond(&n.alt); } fn visit_import_default_specifier(&mut self, n: &ImportDefaultSpecifier) { self.declare_decl(&n.local, Some(Value::Unknown), None, false); } fn visit_import_named_specifier(&mut self, n: &ImportNamedSpecifier) { self.declare_decl(&n.local, Some(Value::Unknown), None, false); } fn visit_import_star_as_specifier(&mut self, n: &ImportStarAsSpecifier) { self.declare_decl(&n.local, Some(Value::Unknown), None, false); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_jsx_element_name(&mut self, n: &JSXElementName) { let ctx = Ctx { in_pat_of_var_decl: false, in_pat_of_param: false, in_catch_param: false, var_decl_kind_of_pat: None, in_pat_of_var_decl_with_init: None, ..self.ctx }; n.visit_children_with(&mut *self.with_ctx(ctx)); if let JSXElementName::Ident(i) = n { self.with_ctx(ctx).report_usage(i); } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip(self, e)))] fn visit_member_expr(&mut self, e: &MemberExpr) { { let ctx = Ctx { is_id_ref: false, ..self.ctx }; e.obj.visit_with(&mut *self.with_ctx(ctx)); } if let MemberProp::Computed(c) = &e.prop { c.visit_with(self); } for_each_id_ref_in_expr(&e.obj, &mut |obj| { let v = self.data.var_or_default(obj.to_id()); v.mark_has_property_access(); if let MemberProp::Computed(prop) = &e.prop { match &*prop.expr { Expr::Lit(Lit::Str(s)) if s.value.parse::<f64>().is_err() => { v.add_accessed_property(s.value.clone()); } _ => { v.mark_indexed_with_dynamic_key(); } } } if let MemberProp::Ident(prop) = &e.prop { v.add_accessed_property(prop.sym.clone()); } }) } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_method_prop(&mut self, n: &MethodProp) { n.function.decorators.visit_with(self); self.with_child(n.function.ctxt, ScopeKind::Fn, |a| { n.key.visit_with(a); { let ctx = Ctx { in_pat_of_param: true, ..a.ctx }; n.function.params.visit_with(&mut *a.with_ctx(ctx)); } n.function.visit_with(a); }); } fn visit_module(&mut self, n: &Module) { let ctx = Ctx { is_top_level: true, ..self.ctx }; n.visit_children_with(&mut *self.with_ctx(ctx)) } fn visit_named_export(&mut self, n: &NamedExport) { if n.src.is_some() { return; } n.visit_children_with(self); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_new_expr(&mut self, n: &NewExpr) { { n.callee.visit_with(self); let ctx = Ctx { is_id_ref: true, ..self.ctx }; n.args.visit_with(&mut *self.with_ctx(ctx)); if call_may_mutate(&n.callee, self.expr_ctx) { if let Some(args) = &n.args { for a in args { for_each_id_ref_in_expr(&a.expr, &mut |id| { self.data.mark_property_mutation(id.to_id()); }); } } } } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_param(&mut self, n: &Param) { let ctx = Ctx { in_pat_of_param: false, ..self.ctx }; n.decorators.visit_with(&mut *self.with_ctx(ctx)); let ctx = Ctx { in_pat_of_param: true, var_decl_kind_of_pat: None, is_id_ref: true, ..self.ctx }; n.pat.visit_with(&mut *self.with_ctx(ctx)); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_pat(&mut self, n: &Pat) { match n { Pat::Ident(i) => { i.visit_with(self); } _ => { let ctx = Ctx { in_decl_with_no_side_effect_for_member_access: false, ..self.ctx }; n.visit_children_with(&mut *self.with_ctx(ctx)); } } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_private_method(&mut self, n: &PrivateMethod) { n.function.decorators.visit_with(self); self.with_child(n.function.ctxt, ScopeKind::Fn, |a| { n.key.visit_with(a); { let ctx = Ctx { in_pat_of_param: true, ..a.ctx }; n.function.params.visit_with(&mut *a.with_ctx(ctx)); } n.function.visit_with(a); }); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_private_prop(&mut self, n: &PrivateProp) { let ctx = Ctx { is_id_ref: true, ..self.ctx }; n.visit_children_with(&mut *self.with_ctx(ctx)); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_prop(&mut self, n: &Prop) { let ctx = Ctx { is_id_ref: true, ..self.ctx }; n.visit_children_with(&mut *self.with_ctx(ctx)); if let Prop::Shorthand(i) = n { self.report_usage(i); } } fn visit_script(&mut self, n: &Script) { let ctx = Ctx { is_top_level: true, ..self.ctx }; n.visit_children_with(&mut *self.with_ctx(ctx)) } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_setter_prop(&mut self, n: &SetterProp) { self.with_child(SyntaxContext::empty(), ScopeKind::Fn, |a| { n.key.visit_with(a); { let ctx = Ctx { in_pat_of_param: true, ..a.ctx }; n.param.visit_with(&mut *a.with_ctx(ctx)); } n.body.visit_with(a); }); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_spread_element(&mut self, e: &SpreadElement) { e.visit_children_with(self); for_each_id_ref_in_expr(&e.expr, &mut |i| { self.data .var_or_default(i.to_id()) .mark_indexed_with_dynamic_key(); }); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_stmt(&mut self, n: &Stmt) { let ctx = Ctx { in_await_arg: false, is_id_ref: true, ..self.ctx }; n.visit_children_with(&mut *self.with_ctx(ctx)); } fn visit_stmts(&mut self, stmts: &[Stmt]) { let mut had_cond = false; for stmt in stmts { let ctx = Ctx { in_cond: self.ctx.in_cond || had_cond, is_id_ref: true, ..self.ctx }; stmt.visit_with(&mut *self.with_ctx(ctx)); had_cond |= can_end_conditionally(stmt); } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip(self, e)))] fn visit_super_prop_expr(&mut self, e: &SuperPropExpr) { if let SuperProp::Computed(c) = &e.prop { let ctx = Ctx { is_id_ref: false, ..self.ctx }; c.visit_with(&mut *self.with_ctx(ctx)); } } fn visit_switch_case(&mut self, n: &SwitchCase) { let ctx = Ctx { is_id_ref: false, ..self.ctx }; n.visit_children_with(&mut *self.with_ctx(ctx)) } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_switch_stmt(&mut self, n: &SwitchStmt) { n.discriminant.visit_with(self); let mut fallthrough = false; for case in n.cases.iter() { let ctx = Ctx { in_cond: true, ..self.ctx }; if fallthrough { self.with_ctx(ctx).visit_in_cond(&case.test); self.with_ctx(ctx).visit_in_cond(&case.cons); } else { self.with_ctx(ctx).visit_in_cond(case); } fallthrough = !case.cons.iter().rev().any(|s| s.terminates()) } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_tagged_tpl(&mut self, n: &TaggedTpl) { { let ctx = Ctx { is_id_ref: false, ..self.ctx }; n.tag.visit_with(&mut *self.with_ctx(ctx)); } { let ctx = Ctx { is_id_ref: true, ..self.ctx }; // Bypass visit_tpl n.tpl.visit_children_with(&mut *self.with_ctx(ctx)) } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_tpl(&mut self, n: &Tpl) { let ctx = Ctx { is_id_ref: false, ..self.ctx }; n.visit_children_with(&mut *self.with_ctx(ctx)) } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_try_stmt(&mut self, n: &TryStmt) { let ctx = Ctx { in_cond: true, ..self.ctx }; self.with_ctx(ctx).visit_children_in_cond(n); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_unary_expr(&mut self, n: &UnaryExpr) { if n.op == op!("delete") { self.mark_mutation_if_member(n.arg.as_member()); } n.visit_children_with(self); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_update_expr(&mut self, n: &UpdateExpr) { n.visit_children_with(self); self.report_assign_expr_if_ident(n.arg.as_ident(), true, Value::Known(Type::Num)); self.mark_mutation_if_member(n.arg.as_member()); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_var_decl(&mut self, n: &VarDecl) { let ctx = Ctx { var_decl_kind_of_pat: Some(n.kind), in_await_arg: false, ..self.ctx }; n.visit_children_with(&mut *self.with_ctx(ctx)); for decl in &n.decls { if let (Pat::Ident(var), Some(init)) = (&decl.name, decl.init.as_deref()) { let mut v = None; for id in collect_infects_from( init, AliasConfig { marks: self.marks, ignore_named_child_scope: true, ..Default::default() }, ) { if v.is_none() { v = Some(self.data.var_or_default(var.to_id())); } v.as_mut().unwrap().add_infects_to(id.clone()); } } } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip(self, e)))] fn visit_var_declarator(&mut self, e: &VarDeclarator) { let prevent_inline = matches!(&e.name, Pat::Ident(BindingIdent { id: Ident { sym: arguments, .. }, .. }) if (&**arguments == "arguments")); { let ctx = Ctx { inline_prevented: self.ctx.inline_prevented || prevent_inline, in_pat_of_var_decl: true, in_pat_of_var_decl_with_init: e .init .as_ref() .map(|init| init.get_type(self.expr_ctx)), in_decl_with_no_side_effect_for_member_access: e .init .as_deref() .map(is_safe_to_access_prop) .unwrap_or(false), ..self.ctx }; e.name.visit_with(&mut *self.with_ctx(ctx)); } { let ctx = Ctx { inline_prevented: self.ctx.inline_prevented || prevent_inline, in_pat_of_var_decl: false, is_id_ref: true, ..self.ctx }; if self.marks.is_some() { if let VarDeclarator { name: Pat::Ident(id), init: Some(init), definite: false, .. } = e { let id = id.to_id(); self.used_recursively.insert( id.clone(), RecursiveUsage::Var { can_ignore: !init.may_have_side_effects(self.expr_ctx), }, ); e.init.visit_with(&mut *self.with_ctx(ctx)); self.used_recursively.remove(&id); return; } } e.init.visit_with(&mut *self.with_ctx(ctx)); } } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_while_stmt(&mut self, n: &WhileStmt) { n.test.visit_with(&mut *self.with_ctx(Ctx { executed_multiple_time: true, ..self.ctx })); let ctx = Ctx { executed_multiple_time: true, in_cond: true, ..self.ctx }; self.with_ctx(ctx).visit_in_cond(&n.body); } #[cfg_attr(feature = "tracing-spans", tracing::instrument(skip_all))] fn visit_with_stmt(&mut self, n: &WithStmt) { self.scope.mark_with_stmt(); n.visit_children_with(self); } } /// - `a` => `a` /// - `a ? b : c` => `b`, `c` fn for_each_id_ref_in_expr(e: &Expr, op: &mut impl FnMut(&Ident)) { match e { Expr::Ident(i) => op(i), Expr::Cond(c) => { for_each_id_ref_in_expr(&c.cons, op); for_each_id_ref_in_expr(&c.alt, op); } Expr::Bin(b @ BinExpr { op: bin_op, .. }) if bin_op.may_short_circuit() => { for_each_id_ref_in_expr(&b.left, op); for_each_id_ref_in_expr(&b.right, op); } Expr::Class(c) => { for_each_id_ref_in_class(&c.class, op); } Expr::Fn(f) => { for_each_id_ref_in_fn(&f.function, op); } Expr::Seq(s) => { for_each_id_ref_in_expr(s.exprs.last().unwrap(), op); } Expr::Array(arr) => { arr.elems.iter().flatten().for_each(|e| { for_each_id_ref_in_expr(&e.expr, op); }); } Expr::Object(obj) => { obj.props.iter().for_each(|p| match p { PropOrSpread::Spread(p) => { for_each_id_ref_in_expr(&p.expr, op); } PropOrSpread::Prop(p) => match &**p { Prop::Shorthand(p) => { op(p); } Prop::KeyValue(p) => { for_each_id_ref_in_prop_name(&p.key, op); for_each_id_ref_in_expr(&p.value, op); } Prop::Assign(p) => { for_each_id_ref_in_expr(&p.value, op); } Prop::Getter(p) => { for_each_id_ref_in_prop_name(&p.key, op); } Prop::Setter(p) => { for_each_id_ref_in_prop_name(&p.key, op); for_each_id_ref_in_pat(&p.param, op); } Prop::Method(p) => { for_each_id_ref_in_fn(&p.function, op); } }, }); } _ => {} } } fn for_each_id_ref_in_class(c: &Class, op: &mut impl FnMut(&Ident)) { c.body.iter().for_each(|m| match m { ClassMember::Constructor(m) => { for_each_id_ref_in_prop_name(&m.key, op); m.params.iter().for_each(|p| match p { ParamOrTsParamProp::TsParamProp(..) => { unreachable!() } ParamOrTsParamProp::Param(p) => { for_each_id_ref_in_pat(&p.pat, op); } }); } ClassMember::Method(m) => { for_each_id_ref_in_prop_name(&m.key, op); for_each_id_ref_in_fn(&m.function, op); } ClassMember::PrivateMethod(m) => { for_each_id_ref_in_fn(&m.function, op); } ClassMember::ClassProp(m) => { for_each_id_ref_in_prop_name(&m.key, op); if let Some(value) = &m.value { for_each_id_ref_in_expr(value, op); } } ClassMember::PrivateProp(m) => { if let Some(value) = &m.value { for_each_id_ref_in_expr(value, op); } } ClassMember::AutoAccessor(m) => { if let Key::Public(key) = &m.key { for_each_id_ref_in_prop_name(key, op); } if let Some(v) = &m.value { for_each_id_ref_in_expr(v, op); } } ClassMember::Empty(..) | ClassMember::StaticBlock(..) | ClassMember::TsIndexSignature(..) => {} }); } fn for_each_id_ref_in_prop_name(p: &PropName, op: &mut impl FnMut(&Ident)) { if let PropName::Computed(p) = p { for_each_id_ref_in_expr(&p.expr, op); } } fn for_each_id_ref_in_pat(p: &Pat, op: &mut impl FnMut(&Ident)) { match p { Pat::Ident(..) => { // IdentifierBinding is not IdentifierReference } Pat::Array(p) => { p.elems.iter().flatten().for_each(|e| { for_each_id_ref_in_pat(e, op); }); } Pat::Rest(p) => { for_each_id_ref_in_pat(&p.arg, op); } Pat::Object(p) => { p.props.iter().for_each(|p| match p { ObjectPatProp::KeyValue(p) => { for_each_id_ref_in_prop_name(&p.key, op); for_each_id_ref_in_pat(&p.value, op); } ObjectPatProp::Assign(p) => { // We skip key because it's IdentifierBinding if let Some(value) = &p.value { for_each_id_ref_in_expr(value, op); } } ObjectPatProp::Rest(p) => { for_each_id_ref_in_pat(&p.arg, op); } }); } Pat::Assign(p) => { for_each_id_ref_in_pat(&p.left, op); for_each_id_ref_in_expr(&p.right, op); } Pat::Invalid(..) => {} Pat::Expr(p) => { for_each_id_ref_in_expr(p, op); } } } fn for_each_id_ref_in_fn(f: &Function, op: &mut impl FnMut(&Ident)) { for p in &f.params { for_each_id_ref_in_pat(&p.pat, op); } } // Support for pure_getters fn is_safe_to_access_prop(e: &Expr) -> bool { match e { Expr::Lit(Lit::Null(..)) => false, Expr::Lit(..) | Expr::Array(..) | Expr::Fn(..) | Expr::Arrow(..) | Expr::Update(..) => true, _ => false, } } fn call_may_mutate(expr: &Expr, expr_ctx: ExprCtx) -> bool { fn is_global_fn_wont_mutate(s: &Ident, unresolved: SyntaxContext) -> bool { s.ctxt == unresolved && matches!( &*s.sym, "JSON" // | "Array" | "String" // | "Object" | "Number" | "Date" | "BigInt" | "Boolean" | "Math" | "Error" | "console" | "clearInterval" | "clearTimeout" | "setInterval" | "setTimeout" | "btoa" | "decodeURI" | "decodeURIComponent" | "encodeURI" | "encodeURIComponent" | "escape" | "eval" | "EvalError" | "Function" | "isFinite" | "isNaN" | "parseFloat" | "parseInt" | "RegExp" | "RangeError" | "ReferenceError" | "SyntaxError" | "TypeError" | "unescape" | "URIError" | "atob" | "globalThis" | "NaN" | "Symbol" | "Promise" ) } if expr.is_pure_callee(expr_ctx) { false } else { match expr { Expr::Ident(i) if is_global_fn_wont_mutate(i, expr_ctx.unresolved_ctxt) => false, Expr::Member(MemberExpr { obj, .. }) => { !matches!(&**obj, Expr::Ident(i) if is_global_fn_wont_mutate(i, expr_ctx.unresolved_ctxt)) } _ => true, } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_usage_analyzer/src/analyzer/storage.rs
Rust
use swc_atoms::Atom; use swc_common::SyntaxContext; use swc_ecma_ast::*; use swc_ecma_utils::{Type, Value}; use super::{ctx::Ctx, ScopeKind}; use crate::alias::Access; pub trait Storage: Sized + Default { type ScopeData: ScopeDataLike; type VarData: VarDataLike; fn scope(&mut self, ctxt: SyntaxContext) -> &mut Self::ScopeData; fn top_scope(&mut self) -> &mut Self::ScopeData; fn var_or_default(&mut self, id: Id) -> &mut Self::VarData; fn merge(&mut self, kind: ScopeKind, child: Self); fn report_usage(&mut self, ctx: Ctx, i: Id); fn report_assign(&mut self, ctx: Ctx, i: Id, is_op: bool, ty: Value<Type>); fn declare_decl( &mut self, ctx: Ctx, i: &Ident, init_type: Option<Value<Type>>, kind: Option<VarDeclKind>, ) -> &mut Self::VarData; fn get_initialized_cnt(&self) -> usize; fn truncate_initialized_cnt(&mut self, len: usize); fn mark_property_mutation(&mut self, id: Id); } pub trait ScopeDataLike: Sized + Default + Clone { fn add_declared_symbol(&mut self, id: &Ident); fn merge(&mut self, other: Self, is_child: bool); fn mark_used_arguments(&mut self); fn mark_eval_called(&mut self); fn mark_with_stmt(&mut self); } pub trait VarDataLike: Sized { /// See `declared_as_fn_param` of [crate::analyzer::VarUsageInfo]. fn mark_declared_as_fn_param(&mut self); fn mark_declared_as_fn_decl(&mut self); fn mark_declared_as_fn_expr(&mut self); fn mark_declared_as_for_init(&mut self); fn mark_has_property_access(&mut self); fn mark_used_as_callee(&mut self); fn mark_used_as_arg(&mut self); fn mark_indexed_with_dynamic_key(&mut self); fn add_accessed_property(&mut self, name: Atom); fn mark_used_as_ref(&mut self); fn add_infects_to(&mut self, other: Access); fn prevent_inline(&mut self); fn mark_as_exported(&mut self); fn mark_initialized_with_safe_value(&mut self); fn mark_as_pure_fn(&mut self); fn mark_used_above_decl(&mut self); fn mark_used_recursively(&mut self); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_usage_analyzer/src/lib.rs
Rust
//! This crate is an internal crate that is extracted just to reduce compile //! time. Do not use this crate directly, and this package does not follow //! semver. #![allow(clippy::mutable_key_type)] pub mod alias; pub mod analyzer; pub mod marks; pub mod util;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_usage_analyzer/src/marks.rs
Rust
#![allow(dead_code)] use swc_common::{Mark, SyntaxContext}; #[derive(Debug, Clone, Copy)] pub struct Marks { /// `/** @const */`. pub const_ann: Mark, /// Check for `/*#__NOINLINE__*/` pub noinline: Mark, /// Check for `/*#__PURE__*/` pub pure: Mark, /// This is applied to [swc_ecma_ast::BlockStmt] which is injected to /// preserve the side effects. pub fake_block: Mark, pub top_level_ctxt: SyntaxContext, pub unresolved_mark: Mark, } impl Marks { #[allow(clippy::new_without_default)] pub fn new() -> Self { fn m() -> Mark { Mark::new() } Marks { const_ann: m(), noinline: m(), pure: m(), fake_block: m(), top_level_ctxt: SyntaxContext::empty().apply_mark(m()), unresolved_mark: m(), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_usage_analyzer/src/util.rs
Rust
use swc_ecma_ast::Stmt; pub fn is_global_var_with_pure_property_access(s: &str) -> bool { match s { "JSON" | "Array" | "Set" | "Map" | "String" | "Object" | "Number" | "Date" | "BigInt" | "Boolean" | "Math" | "Error" | "Reflect" => return true, _ => {} } matches!( s, "console" | "clearInterval" | "clearTimeout" | "setInterval" | "setTimeout" | "setImmediate" | "btoa" | "decodeURI" | "decodeURIComponent" | "encodeURI" | "encodeURIComponent" | "escape" | "eval" | "EvalError" | "Function" | "isFinite" | "isNaN" | "parseFloat" | "parseInt" | "RegExp" | "RangeError" | "ReferenceError" | "SyntaxError" | "TypeError" | "unescape" | "URIError" | "atob" | "globalThis" | "NaN" | "Symbol" | "Promise" | "WeakRef" | "ArrayBuffer" ) } pub fn can_end_conditionally(s: &Stmt) -> bool { /// ///`ignore_always`: If true, [Stmt::Return] will be ignored. fn can_end(s: &Stmt, ignore_always: bool) -> bool { match s { Stmt::If(s) => { can_end(&s.cons, false) || s.alt .as_deref() .map(|s| can_end(s, false)) .unwrap_or_default() } Stmt::Switch(s) => s .cases .iter() .any(|case| case.cons.iter().any(|s| can_end(s, false))), Stmt::DoWhile(s) => can_end(&s.body, false), Stmt::While(s) => can_end(&s.body, false), Stmt::For(s) => can_end(&s.body, false), Stmt::ForOf(s) => can_end(&s.body, false), Stmt::ForIn(s) => can_end(&s.body, false), Stmt::Return(..) | Stmt::Break(..) | Stmt::Continue(..) => !ignore_always, _ => false, } } can_end(s, true) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_utils/src/constructor.rs
Rust
use std::{iter, mem}; use swc_common::{util::take::Take, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith}; use crate::ExprFactory; pub fn inject_after_super(c: &mut Constructor, exprs: Vec<Box<Expr>>) { if exprs.is_empty() { return; } let body = c.body.as_mut().expect("constructor should have a body"); let mut injector = Injector { exprs, ..Default::default() }; body.visit_mut_with(&mut injector); if !injector.injected { let exprs = injector.exprs.take(); body.stmts .splice(0..0, exprs.into_iter().map(|e| e.into_stmt())); } } #[derive(Default)] struct Injector { exprs: Vec<Box<Expr>>, ignore_return_value: bool, injected: bool, } impl VisitMut for Injector { noop_visit_mut_type!(); fn visit_mut_constructor(&mut self, _: &mut Constructor) { // skip } fn visit_mut_function(&mut self, _: &mut Function) { // skip } fn visit_mut_getter_prop(&mut self, _: &mut GetterProp) { // skip } fn visit_mut_setter_prop(&mut self, _: &mut SetterProp) { // skip } fn visit_mut_expr_stmt(&mut self, node: &mut ExprStmt) { let ignore_return_value = mem::replace(&mut self.ignore_return_value, true); node.visit_mut_children_with(self); self.ignore_return_value = ignore_return_value; } fn visit_mut_seq_expr(&mut self, node: &mut SeqExpr) { if let Some(mut tail) = node.exprs.pop() { let ignore_return_value = mem::replace(&mut self.ignore_return_value, true); node.visit_mut_children_with(self); self.ignore_return_value = ignore_return_value; tail.visit_mut_with(self); node.exprs.push(tail); } } fn visit_mut_expr(&mut self, node: &mut Expr) { let ignore_return_value = self.ignore_return_value; if !matches!(node, Expr::Paren(..) | Expr::Seq(..)) { self.ignore_return_value = false; } node.visit_mut_children_with(self); self.ignore_return_value = ignore_return_value; if let Expr::Call(CallExpr { callee: Callee::Super(..), .. }) = node { self.injected = true; let super_call = node.take(); let exprs = self.exprs.clone(); let exprs = iter::once(Box::new(super_call)).chain(exprs); *node = if ignore_return_value { SeqExpr { span: DUMMY_SP, exprs: exprs.collect(), } .into() } else { let array = ArrayLit { span: DUMMY_SP, elems: exprs.map(ExprOrSpread::from).map(Some).collect(), }; MemberExpr { span: DUMMY_SP, obj: array.into(), prop: ComputedPropName { span: DUMMY_SP, expr: 0.into(), } .into(), } .into() } } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_utils/src/factory.rs
Rust
use std::iter; use swc_common::{util::take::Take, Span, Spanned, DUMMY_SP}; use swc_ecma_ast::*; /// Extension methods for [Expr]. /// /// Note that many types implements `Into<Expr>` and you can do like /// /// ```rust /// use swc_ecma_utils::ExprFactory; /// /// let _args = vec![0f64.as_arg()]; /// ``` /// /// to create literals. Almost all rust core types implements `Into<Expr>`. #[allow(clippy::wrong_self_convention)] pub trait ExprFactory: Into<Box<Expr>> { /// Creates an [ExprOrSpread] using the given [Expr]. /// /// This is recommended way to create [ExprOrSpread]. /// /// # Example /// /// ```rust /// use swc_common::DUMMY_SP; /// use swc_ecma_ast::*; /// use swc_ecma_utils::ExprFactory; /// /// let first = Lit::Num(Number { /// span: DUMMY_SP, /// value: 0.0, /// raw: None, /// }); /// let _args = vec![first.as_arg()]; /// ``` #[cfg_attr(not(debug_assertions), inline(always))] fn as_arg(self) -> ExprOrSpread { ExprOrSpread { expr: self.into(), spread: None, } } /// Creates an expression statement with `self`. #[cfg_attr(not(debug_assertions), inline(always))] fn into_stmt(self) -> Stmt { ExprStmt { span: DUMMY_SP, expr: self.into(), } .into() } /// Creates a statement whcih return `self`. #[cfg_attr(not(debug_assertions), inline(always))] fn into_return_stmt(self) -> ReturnStmt { ReturnStmt { span: DUMMY_SP, arg: Some(self.into()), } } #[cfg_attr(not(debug_assertions), inline(always))] fn as_callee(self) -> Callee { Callee::Expr(self.into()) } #[cfg_attr(not(debug_assertions), inline(always))] fn as_iife(self) -> CallExpr { CallExpr { span: DUMMY_SP, callee: self.as_callee(), ..Default::default() } } /// create a ArrowExpr which return self /// - `(params) => $self` #[cfg_attr(not(debug_assertions), inline(always))] fn into_lazy_arrow(self, params: Vec<Pat>) -> ArrowExpr { ArrowExpr { params, body: Box::new(BlockStmtOrExpr::Expr(self.into())), ..Default::default() } } /// create a Function which return self /// - `function(params) { return $self; }` #[cfg_attr(not(debug_assertions), inline(always))] fn into_lazy_fn(self, params: Vec<Param>) -> Function { Function { params, decorators: Default::default(), span: DUMMY_SP, body: Some(BlockStmt { span: DUMMY_SP, stmts: vec![self.into_return_stmt().into()], ..Default::default() }), ..Default::default() } } #[cfg_attr(not(debug_assertions), inline(always))] fn into_lazy_auto(self, params: Vec<Pat>, support_arrow: bool) -> Expr { if support_arrow { self.into_lazy_arrow(params).into() } else { self.into_lazy_fn(params.into_iter().map(From::from).collect()) .into_fn_expr(None) .into() } } /// create a var declartor using self as init /// - `var name = expr` #[cfg_attr(not(debug_assertions), inline(always))] fn into_var_decl(self, kind: VarDeclKind, name: Pat) -> VarDecl { let var_declarator = VarDeclarator { span: DUMMY_SP, name, init: Some(self.into()), definite: false, }; VarDecl { kind, decls: vec![var_declarator], ..Default::default() } } #[cfg_attr(not(debug_assertions), inline(always))] fn into_new_expr(self, span: Span, args: Option<Vec<ExprOrSpread>>) -> NewExpr { NewExpr { span, callee: self.into(), args, ..Default::default() } } #[cfg_attr(not(debug_assertions), inline(always))] fn apply(self, span: Span, this: Box<Expr>, args: Vec<ExprOrSpread>) -> Expr { let apply = self.make_member(IdentName::new("apply".into(), span)); CallExpr { span, callee: apply.as_callee(), args: iter::once(this.as_arg()).chain(args).collect(), ..Default::default() } .into() } #[cfg_attr(not(debug_assertions), inline(always))] fn call_fn(self, span: Span, args: Vec<ExprOrSpread>) -> Expr { CallExpr { span, args, callee: self .make_member(IdentName::new("call".into(), span)) .as_callee(), ..Default::default() } .into() } #[cfg_attr(not(debug_assertions), inline(always))] fn as_call(self, span: Span, args: Vec<ExprOrSpread>) -> Expr { CallExpr { span, args, callee: self.as_callee(), ..Default::default() } .into() } #[cfg_attr(not(debug_assertions), inline(always))] fn as_fn_decl(self) -> Option<FnDecl> { match *self.into() { Expr::Fn(FnExpr { ident: Some(ident), function, }) => Some(FnDecl { ident, declare: false, function, }), _ => None, } } #[cfg_attr(not(debug_assertions), inline(always))] fn as_class_decl(self) -> Option<ClassDecl> { match *self.into() { Expr::Class(ClassExpr { ident: Some(ident), class, }) => Some(ClassDecl { ident, declare: false, class, }), _ => None, } } #[cfg_attr(not(debug_assertions), inline(always))] fn wrap_with_paren(self) -> Expr { let expr = self.into(); let span = expr.span(); ParenExpr { expr, span }.into() } /// Creates a binary expr `$self === ` #[cfg_attr(not(debug_assertions), inline(always))] fn make_eq<T>(self, right: T) -> Expr where T: Into<Expr>, { self.make_bin(op!("==="), right) } /// Creates a binary expr `$self $op $rhs` #[cfg_attr(not(debug_assertions), inline(always))] fn make_bin<T>(self, op: BinaryOp, right: T) -> Expr where T: Into<Expr>, { let right = Box::new(right.into()); BinExpr { span: DUMMY_SP, left: self.into(), op, right, } .into() } /// Creates a assign expr `$lhs $op $self` #[cfg_attr(not(debug_assertions), inline(always))] fn make_assign_to(self, op: AssignOp, left: AssignTarget) -> Expr { let right = self.into(); AssignExpr { span: DUMMY_SP, left, op, right, } .into() } #[cfg_attr(not(debug_assertions), inline(always))] fn make_member(self, prop: IdentName) -> MemberExpr { MemberExpr { obj: self.into(), span: DUMMY_SP, prop: MemberProp::Ident(prop), } } #[cfg_attr(not(debug_assertions), inline(always))] fn computed_member<T>(self, prop: T) -> MemberExpr where T: Into<Box<Expr>>, { MemberExpr { obj: self.into(), span: DUMMY_SP, prop: MemberProp::Computed(ComputedPropName { span: DUMMY_SP, expr: prop.into(), }), } } } impl<T: Into<Box<Expr>>> ExprFactory for T {} pub trait IntoIndirectCall where Self: std::marker::Sized, { type Item; fn into_indirect(self) -> Self::Item; } impl IntoIndirectCall for CallExpr { type Item = CallExpr; #[cfg_attr(not(debug_assertions), inline(always))] fn into_indirect(self) -> CallExpr { let callee = self.callee.into_indirect(); CallExpr { callee, ..self } } } impl IntoIndirectCall for Callee { type Item = Callee; #[cfg_attr(not(debug_assertions), inline(always))] fn into_indirect(self) -> Callee { SeqExpr { span: DUMMY_SP, exprs: vec![0f64.into(), self.expect_expr()], } .as_callee() } } impl IntoIndirectCall for TaggedTpl { type Item = TaggedTpl; #[cfg_attr(not(debug_assertions), inline(always))] fn into_indirect(mut self) -> Self { Self { tag: Box::new( SeqExpr { span: DUMMY_SP, exprs: vec![0f64.into(), self.tag.take()], } .into(), ), ..self } } } pub trait FunctionFactory: Into<Box<Function>> { #[cfg_attr(not(debug_assertions), inline(always))] fn into_fn_expr(self, ident: Option<Ident>) -> FnExpr { FnExpr { ident, function: self.into(), } } #[cfg_attr(not(debug_assertions), inline(always))] fn into_fn_decl(self, ident: Ident) -> FnDecl { FnDecl { ident, declare: false, function: self.into(), } } #[cfg_attr(not(debug_assertions), inline(always))] fn into_method_prop(self, key: PropName) -> MethodProp { MethodProp { key, function: self.into(), } } } impl<T: Into<Box<Function>>> FunctionFactory for T {}
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_utils/src/function/fn_env_hoister.rs
Rust
use std::mem; use indexmap::IndexMap; use rustc_hash::FxBuildHasher; use swc_atoms::Atom; use swc_common::{util::take::Take, Span, Spanned, SyntaxContext, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith}; use crate::ExprFactory; #[derive(Default)] struct SuperField { computed: Option<Ident>, ident: IndexMap<Atom, Ident, FxBuildHasher>, } /// Don't use it against function, it will stop if come across any function /// use it against function body #[derive(Default)] pub struct FnEnvHoister { unresolved_ctxt: SyntaxContext, this: Option<Ident>, args: Option<Ident>, new_target: Option<Ident>, super_get: SuperField, super_set: SuperField, super_update: SuperField, arguments_disabled: bool, this_disabled: bool, super_disabled: bool, in_pat: bool, // extra ident for super["xx"] += 123 extra_ident: Vec<Ident>, } impl FnEnvHoister { pub fn new(unresolved_ctxt: SyntaxContext) -> Self { Self { unresolved_ctxt, ..Default::default() } } /// Disable hoisting of `arguments` pub fn disable_arguments(&mut self) { self.arguments_disabled = true; } /// Disable hoisting of `this` pub fn disable_this(&mut self) { self.this_disabled = true; } /// Disable hoisting of nodes realted to `super` pub fn disable_super(&mut self) { self.super_disabled = true; } pub fn take(&mut self) -> Self { let mut new = Self { unresolved_ctxt: self.unresolved_ctxt, ..Default::default() }; mem::swap(self, &mut new); new } pub fn to_decl(self) -> Vec<VarDeclarator> { let Self { this, args, new_target, super_get, super_set, super_update, .. } = self; let mut decls = Vec::with_capacity(3); if let Some(this_id) = this { decls.push(VarDeclarator { span: DUMMY_SP, name: this_id.into(), init: Some(ThisExpr { span: DUMMY_SP }.into()), definite: false, }); } if let Some(id) = args { decls.push(VarDeclarator { span: DUMMY_SP, name: id.into(), init: Some(Ident::new_no_ctxt("arguments".into(), DUMMY_SP).into()), definite: false, }); } if let Some(id) = new_target { decls.push(VarDeclarator { span: DUMMY_SP, name: id.into(), init: Some( MetaPropExpr { span: DUMMY_SP, kind: MetaPropKind::NewTarget, } .into(), ), definite: false, }); } extend_super(&mut decls, super_get, super_set, super_update); decls } pub fn to_stmt(self) -> Option<Stmt> { let decls = self.to_decl(); if decls.is_empty() { None } else { Some( VarDecl { kind: VarDeclKind::Var, decls, ..Default::default() } .into(), ) } } pub fn to_stmt_in_subclass(self) -> (Option<Stmt>, Option<Ident>) { let Self { this, args, new_target, super_get, super_set, super_update, .. } = self; let mut decls = Vec::with_capacity(3); if let Some(this_id) = &this { decls.push(VarDeclarator { span: DUMMY_SP, name: this_id.clone().into(), init: None, definite: false, }); } if let Some(id) = args { decls.push(VarDeclarator { span: DUMMY_SP, name: id.into(), init: Some(Ident::new_no_ctxt("arguments".into(), DUMMY_SP).into()), definite: false, }); } if let Some(id) = new_target { decls.push(VarDeclarator { span: DUMMY_SP, name: id.into(), init: Some( MetaPropExpr { span: DUMMY_SP, kind: MetaPropKind::NewTarget, } .into(), ), definite: false, }); } extend_super(&mut decls, super_get, super_set, super_update); if decls.is_empty() { (None, None) } else { ( Some( VarDecl { kind: VarDeclKind::Var, decls, ..Default::default() } .into(), ), this, ) } } fn get_this(&mut self) -> Ident { self.this .get_or_insert_with(|| private_ident!("_this")) .clone() } fn super_get(&mut self, prop_name: &Atom, prop_span: Span) -> Ident { if let Some(callee) = self.super_get.ident.get(prop_name) { callee.clone() } else { let ident = private_ident!(prop_span, format!("_superprop_get_{}", prop_name)); self.super_get .ident .insert(prop_name.clone(), ident.clone()); ident } } fn super_get_computed(&mut self, span: Span) -> Ident { self.super_get .computed .get_or_insert_with(|| private_ident!(span, "_superprop_get")) .clone() } fn super_set(&mut self, prop_name: &Atom, prop_span: Span) -> Ident { if let Some(callee) = self.super_set.ident.get(prop_name) { callee.clone() } else { let ident = private_ident!(prop_span, format!("_superprop_set_{}", prop_name)); self.super_set .ident .insert(prop_name.clone(), ident.clone()); ident } } fn super_set_computed(&mut self, span: Span) -> Ident { self.super_set .computed .get_or_insert_with(|| private_ident!(span, "_superprop_set")) .clone() } fn super_update(&mut self, prop_name: &Atom, prop_span: Span) -> Ident { if let Some(callee) = self.super_update.ident.get(prop_name) { callee.clone() } else { self.super_get .ident .entry(prop_name.clone()) .or_insert_with(|| { private_ident!(prop_span, format!("_superprop_get_{}", prop_name)) }); self.super_set .ident .entry(prop_name.clone()) .or_insert_with(|| { private_ident!(prop_span, format!("_superprop_set_{}", prop_name)) }); let ident = private_ident!(prop_span, format!("_superprop_update_{}", prop_name)); self.super_update .ident .insert(prop_name.clone(), ident.clone()); ident } } fn super_update_computed(&mut self, span: Span) -> Ident { self.super_get .computed .get_or_insert_with(|| private_ident!(span, "_superprop_get")); self.super_set .computed .get_or_insert_with(|| private_ident!(span, "_superprop_set")); self.super_update .computed .get_or_insert_with(|| private_ident!(span, "_superprop_update")) .clone() } } impl VisitMut for FnEnvHoister { noop_visit_mut_type!(fail); fn visit_mut_assign_target_pat(&mut self, n: &mut AssignTargetPat) { let in_pat = self.in_pat; self.in_pat = true; n.visit_mut_children_with(self); self.in_pat = in_pat; } fn visit_mut_block_stmt(&mut self, b: &mut BlockStmt) { b.visit_mut_children_with(self); // we will not vist into fn/class so it's fine if !self.extra_ident.is_empty() { b.stmts.insert( 0, VarDecl { kind: VarDeclKind::Var, decls: self .extra_ident .take() .into_iter() .map(|ident| VarDeclarator { span: DUMMY_SP, name: ident.into(), init: None, definite: false, }) .collect(), ..Default::default() } .into(), ) } } fn visit_mut_block_stmt_or_expr(&mut self, b: &mut BlockStmtOrExpr) { b.visit_mut_children_with(self); // we will not vist into fn/class so it's fine if !self.extra_ident.is_empty() { if let BlockStmtOrExpr::Expr(e) = b { *b = BlockStmtOrExpr::BlockStmt(BlockStmt { stmts: vec![ Stmt::Decl(Decl::Var(Box::new(VarDecl { kind: VarDeclKind::Var, decls: self .extra_ident .take() .into_iter() .map(|ident| VarDeclarator { span: DUMMY_SP, name: ident.into(), init: None, definite: false, }) .collect(), ..Default::default() }))), Stmt::Return(ReturnStmt { span: e.span(), arg: Some(e.take()), }), ], ..Default::default() }) } } } /// Don't recurse into constructor fn visit_mut_class(&mut self, _: &mut Class) {} fn visit_mut_expr(&mut self, e: &mut Expr) { match e { Expr::Ident(Ident { ctxt, sym, .. }) if !self.arguments_disabled && *sym == "arguments" && (*ctxt == self.unresolved_ctxt || *ctxt == SyntaxContext::empty()) => { let arguments = self .args .get_or_insert_with(|| private_ident!("_arguments")); *e = arguments.clone().into(); } Expr::This(..) if !self.this_disabled => { let this = self.get_this(); *e = this.into(); } Expr::MetaProp(MetaPropExpr { kind: MetaPropKind::NewTarget, .. }) => { let target = self .new_target .get_or_insert_with(|| private_ident!("_newtarget")); *e = target.clone().into(); } // super.foo = 123 => super_get_foo = (value) => super.foo = value Expr::Assign(AssignExpr { left, right, span, op, }) => { let expr = match left { AssignTarget::Simple(e) => e, AssignTarget::Pat(..) => { e.visit_mut_children_with(self); return; } }; if !self.super_disabled { if let SimpleAssignTarget::SuperProp(super_prop) = &mut *expr { let left_span = super_prop.span; match &mut super_prop.prop { SuperProp::Computed(c) => { let callee = self.super_set_computed(left_span); let op = op.to_update(); let args = if let Some(op) = op { let tmp = private_ident!("tmp"); self.extra_ident.push(tmp.clone()); vec![ Expr::Assign(AssignExpr { span: DUMMY_SP, left: tmp.clone().into(), op: op!("="), right: c.expr.take(), }) .as_arg(), Expr::Bin(BinExpr { span: DUMMY_SP, left: Box::new(Expr::Call(CallExpr { span: DUMMY_SP, callee: self .super_get_computed(DUMMY_SP) .as_callee(), args: vec![tmp.as_arg()], ..Default::default() })), op, right: right.take(), }) .as_arg(), ] } else { vec![c.expr.take().as_arg(), right.take().as_arg()] }; *e = CallExpr { span: *span, args, callee: callee.as_callee(), ..Default::default() } .into(); } SuperProp::Ident(id) => { let callee = self.super_set(&id.sym, left_span); *e = CallExpr { span: *span, args: vec![(if let Some(op) = op.to_update() { Box::new(Expr::Bin(BinExpr { span: DUMMY_SP, left: Box::new( self.super_get(&id.sym, id.span) .as_call(id.span, Vec::new()), ), op, right: right.take(), })) } else { right.take() }) .as_arg()], callee: callee.as_callee(), ..Default::default() } .into(); } } } } e.visit_mut_children_with(self) } // super.foo() => super_get_foo = () => super.foo Expr::Call(CallExpr { span, callee: Callee::Expr(expr), args, .. }) => { if !self.super_disabled { if let Expr::SuperProp(super_prop) = &mut **expr { match &mut super_prop.prop { SuperProp::Computed(c) => { let callee = self.super_get_computed(super_prop.span); let call: Expr = CallExpr { span: *span, args: vec![c.expr.take().as_arg()], callee: callee.as_callee(), ..Default::default() } .into(); let mut new_args = args.take(); new_args.insert(0, self.get_this().as_arg()); *e = call.call_fn(*span, new_args); } SuperProp::Ident(id) => { let callee = self.super_get(&id.sym, super_prop.span); let call: Expr = CallExpr { span: *span, args: Vec::new(), callee: callee.as_callee(), ..Default::default() } .into(); let mut new_args = args.take(); new_args.insert(0, self.get_this().as_arg()); *e = call.call_fn(*span, new_args); } } }; } e.visit_mut_children_with(self) } // super.foo ++ Expr::Update(UpdateExpr { arg, .. }) if arg.is_super_prop() => { let in_pat = self.in_pat; // NOTE: It's not in pat, but we need the `update` trick self.in_pat = true; arg.visit_mut_with(self); self.in_pat = in_pat; } Expr::SuperProp(SuperPropExpr { prop, span, .. }) if !self.super_disabled => match prop { SuperProp::Computed(c) => { c.expr.visit_mut_children_with(self); *e = if self.in_pat { Expr::from(CallExpr { span: *span, args: vec![c.expr.take().as_arg()], callee: self.super_update_computed(*span).as_callee(), ..Default::default() }) .make_member("_".into()) .into() } else { CallExpr { span: *span, args: vec![c.expr.take().as_arg()], callee: self.super_get_computed(*span).as_callee(), ..Default::default() } .into() }; } SuperProp::Ident(id) => { *e = if self.in_pat { self.super_update(&id.sym, *span) .make_member(quote_ident!("_")) .into() } else { CallExpr { span: *span, args: Vec::new(), callee: self.super_get(&id.sym, *span).as_callee(), ..Default::default() } .into() }; } }, _ => e.visit_mut_children_with(self), } } /// Don't recurse into fn fn visit_mut_function(&mut self, _: &mut Function) {} /// Don't recurse into getter/setter/method except computed key fn visit_mut_getter_prop(&mut self, p: &mut GetterProp) { if p.key.is_computed() { p.key.visit_mut_with(self); } } fn visit_mut_method_prop(&mut self, p: &mut MethodProp) { if p.key.is_computed() { p.key.visit_mut_with(self); } } fn visit_mut_pat(&mut self, n: &mut Pat) { let in_pat = self.in_pat; self.in_pat = true; n.visit_mut_children_with(self); self.in_pat = in_pat; } fn visit_mut_setter_prop(&mut self, p: &mut SetterProp) { if p.key.is_computed() { p.key.visit_mut_with(self); } } } pub fn init_this(stmts: &mut Vec<Stmt>, this_id: &Ident) { stmts.visit_mut_children_with(&mut InitThis { this_id }) } struct InitThis<'a> { this_id: &'a Ident, } // babel is skip function and class property impl VisitMut for InitThis<'_> { noop_visit_mut_type!(fail); fn visit_mut_class(&mut self, _: &mut Class) {} // babel will transform super() to super(); _this = this // hopefully it will be meaningless // fn visit_mut_stmts(&mut self, stmt: &mut Vec<Stmt>) {} fn visit_mut_expr(&mut self, expr: &mut Expr) { expr.visit_mut_children_with(self); if let Expr::Call( call_expr @ CallExpr { callee: Callee::Super(..), .. }, ) = expr { let span = call_expr.span; *expr = ParenExpr { span, expr: SeqExpr { span, exprs: vec![ Box::new(Expr::Call(call_expr.take())), Box::new(Expr::Assign(AssignExpr { span: DUMMY_SP, left: self.this_id.clone().into(), op: AssignOp::Assign, right: Box::new(Expr::This(ThisExpr { span: DUMMY_SP })), })), ], } .into(), } .into() } } } fn extend_super( decls: &mut Vec<VarDeclarator>, get: SuperField, set: SuperField, update: SuperField, ) { decls.extend(update.ident.into_iter().map(|(key, ident)| { let value = private_ident!("v"); VarDeclarator { span: DUMMY_SP, name: ident.into(), init: Some( ObjectLit { span: DUMMY_SP, props: vec![ Prop::Getter(GetterProp { span: DUMMY_SP, key: PropName::Ident("_".into()), type_ann: None, body: Some(BlockStmt { stmts: vec![Expr::Ident( get.ident .get(&key) .cloned() .expect("getter not found") .without_loc(), ) .as_call(DUMMY_SP, Default::default()) .into_return_stmt() .into()], ..Default::default() }), }), Prop::Setter(SetterProp { span: DUMMY_SP, key: PropName::Ident("_".into()), this_param: None, param: value.clone().into(), body: Some(BlockStmt { stmts: vec![Expr::Ident( set.ident .get(&key) .cloned() .expect("setter not found") .without_loc(), ) .as_call(DUMMY_SP, vec![value.as_arg()]) .into_stmt()], ..Default::default() }), }), ] .into_iter() .map(Box::new) .map(From::from) .collect(), } .into(), ), definite: false, } })); if let Some(id) = update.computed { let prop = private_ident!("_prop"); let value = private_ident!("v"); decls.push(VarDeclarator { span: DUMMY_SP, name: id.into(), init: Some( ArrowExpr { span: DUMMY_SP, params: vec![prop.clone().into()], body: Box::new(BlockStmtOrExpr::Expr(Box::new( ObjectLit { span: DUMMY_SP, props: vec![ Prop::Getter(GetterProp { span: DUMMY_SP, key: PropName::Ident("_".into()), type_ann: None, body: Some(BlockStmt { stmts: vec![Expr::Ident( get.computed .clone() .expect("getter computed not found") .without_loc(), ) .as_call(DUMMY_SP, vec![prop.clone().as_arg()]) .into_return_stmt() .into()], ..Default::default() }), }), Prop::Setter(SetterProp { span: DUMMY_SP, key: PropName::Ident("_".into()), this_param: None, param: value.clone().into(), body: Some(BlockStmt { stmts: vec![Expr::Ident( set.computed .clone() .expect("setter computed not found") .without_loc(), ) .as_call(DUMMY_SP, vec![prop.as_arg(), value.as_arg()]) .into_return_stmt() .into()], ..Default::default() }), }), ] .into_iter() .map(Box::new) .map(From::from) .collect(), } .into(), ))), ..Default::default() } .into(), ), definite: false, }); } decls.extend(get.ident.into_iter().map(|(key, ident)| { VarDeclarator { span: DUMMY_SP, name: ident.without_loc().into(), init: Some( ArrowExpr { span: DUMMY_SP, params: Vec::new(), body: Box::new(BlockStmtOrExpr::Expr(Box::new( SuperPropExpr { obj: Super { span: DUMMY_SP }, prop: SuperProp::Ident(key.into()), span: DUMMY_SP, } .into(), ))), ..Default::default() } .into(), ), definite: false, } })); if let Some(id) = get.computed { let param = private_ident!("_prop"); decls.push(VarDeclarator { span: DUMMY_SP, name: id.without_loc().into(), init: Some( ArrowExpr { span: DUMMY_SP, params: vec![param.clone().into()], body: Box::new(BlockStmtOrExpr::Expr(Box::new( SuperPropExpr { obj: Super { span: DUMMY_SP }, prop: SuperProp::Computed(ComputedPropName { span: DUMMY_SP, expr: Box::new(Expr::Ident(param)), }), span: DUMMY_SP, } .into(), ))), ..Default::default() } .into(), ), definite: false, }); } decls.extend(set.ident.into_iter().map(|(key, ident)| { let value = private_ident!("_value"); VarDeclarator { span: DUMMY_SP, name: ident.without_loc().into(), init: Some( ArrowExpr { span: DUMMY_SP, params: vec![value.clone().into()], body: Box::new(BlockStmtOrExpr::Expr(Box::new( AssignExpr { span: DUMMY_SP, left: SuperPropExpr { obj: Super { span: DUMMY_SP }, prop: SuperProp::Ident(key.into()), span: DUMMY_SP, } .into(), op: op!("="), right: Box::new(Expr::Ident(value)), } .into(), ))), ..Default::default() } .into(), ), definite: false, } })); if let Some(id) = set.computed { let prop = private_ident!("_prop"); let value = private_ident!("_value"); decls.push(VarDeclarator { span: DUMMY_SP, name: id.without_loc().into(), init: Some( ArrowExpr { span: DUMMY_SP, params: vec![prop.clone().into(), value.clone().into()], body: Box::new(BlockStmtOrExpr::Expr(Box::new( AssignExpr { span: DUMMY_SP, left: SuperPropExpr { obj: Super { span: DUMMY_SP }, prop: SuperProp::Computed(ComputedPropName { span: DUMMY_SP, expr: Box::new(Expr::Ident(prop)), }), span: DUMMY_SP, } .into(), op: op!("="), right: Box::new(Expr::Ident(value)), } .into(), ))), ..Default::default() } .into(), ), definite: false, }); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_utils/src/function/function_wrapper.rs
Rust
use std::marker::PhantomData; use swc_common::{util::take::Take, Spanned, DUMMY_SP}; use swc_ecma_ast::*; use crate::ExprFactory; pub struct FunctionWrapper<T> { pub binding_ident: Option<Ident>, pub function: Expr, pub ignore_function_name: bool, pub ignore_function_length: bool, function_ident: Option<Ident>, params: Vec<Param>, _type: PhantomData<T>, } impl<T> FunctionWrapper<T> { /// `get_params` clone only the parameters that count in function length. fn get_params<'a, ParamsIter, Item>(params_iter: ParamsIter) -> Vec<Param> where Item: Into<&'a Param>, ParamsIter: IntoIterator<Item = Item>, { params_iter .into_iter() .map(Into::into) .map_while(|param| match param.pat { Pat::Ident(..) => Some(param.clone()), Pat::Array(..) | Pat::Object(..) => Some(Param { span: param.span, decorators: param.decorators.clone(), pat: private_ident!("_").into(), }), _ => None, }) .collect() } /// /// ```javascript /// (function () { /// var REF = FUNCTION; /// return function NAME(PARAMS) { /// return REF.apply(this, arguments); /// }; /// })() /// ``` fn build_anonymous_expression_wrapper(&mut self) -> Expr { let name_ident = self.binding_ident.take(); let ref_ident = private_ident!("_ref"); let ref_decl: Decl = VarDecl { kind: VarDeclKind::Var, decls: vec![VarDeclarator { span: DUMMY_SP, name: Pat::Ident(ref_ident.clone().into()), init: Some(Box::new(self.function.take())), definite: false, }], ..Default::default() } .into(); let return_fn_stmt = { let fn_expr = self.build_function_forward(ref_ident, name_ident); ReturnStmt { span: DUMMY_SP, arg: Some(Box::new(fn_expr.into())), } } .into(); let block_stmt = BlockStmt { stmts: vec![ref_decl.into(), return_fn_stmt], ..Default::default() }; let function = Box::new(Function { span: DUMMY_SP, body: Some(block_stmt), is_generator: false, is_async: false, ..Default::default() }); FnExpr { ident: None, function, } .as_iife() .into() } /// /// ```javascript /// (function () { /// var REF = FUNCTION; /// function NAME(PARAMS) { /// return REF.apply(this, arguments); /// } /// return NAME; /// })() /// ``` fn build_named_expression_wrapper(&mut self, name_ident: Ident) -> Expr { let ref_ident = self.function_ident.as_ref().map_or_else( || private_ident!("_ref"), |ident| private_ident!(ident.span, format!("_{}", ident.sym)), ); let ref_stmt: Stmt = VarDecl { kind: VarDeclKind::Var, decls: vec![VarDeclarator { span: DUMMY_SP, name: Pat::Ident(ref_ident.clone().into()), init: Some(Box::new(self.function.take())), definite: false, }], ..Default::default() } .into(); let fn_decl_stmt = { let FnExpr { function, .. } = self.build_function_forward(ref_ident, None); FnDecl { ident: name_ident.clone(), declare: false, function, } .into() }; let return_stmt = ReturnStmt { span: DUMMY_SP, arg: Some(Box::new(name_ident.into())), } .into(); let block_stmt = BlockStmt { stmts: vec![ref_stmt, fn_decl_stmt, return_stmt], ..Default::default() }; let function = Box::new(Function { span: DUMMY_SP, body: Some(block_stmt), is_generator: false, is_async: false, ..Default::default() }); FnExpr { ident: None, function, } .as_iife() .into() } /// /// ```javascript /// function NAME(PARAMS) { /// return REF.apply(this, arguments); /// } /// function REF() { /// REF = FUNCTION; /// return REF.apply(this, arguments); /// } /// ``` fn build_declaration_wrapper(&mut self, name_ident: Option<Ident>) -> (FnExpr, FnDecl) { let ref_ident = self.function_ident.as_ref().map_or_else( || private_ident!("_ref"), |ident| private_ident!(ident.span, format!("_{}", ident.sym)), ); // function NAME let fn_expr = self.build_function_forward(ref_ident.clone(), name_ident); let assign_stmt = AssignExpr { span: DUMMY_SP, op: op!("="), left: ref_ident.clone().into(), right: Box::new(self.function.take()), } .into_stmt(); // clone `return REF.apply(this, arguments);` let return_ref_apply_stmt = fn_expr .function .body .as_ref() .expect("The `fn_expr` we construct cannot be None") .stmts[0] .clone(); let ref_fn_block_stmt = BlockStmt { stmts: vec![assign_stmt, return_ref_apply_stmt], ..Default::default() }; // function REF let ref_decl = FnDecl { declare: false, ident: ref_ident, function: Box::new(Function { span: DUMMY_SP, is_async: false, is_generator: false, params: self.params.take(), body: Some(ref_fn_block_stmt), ..Default::default() }), }; (fn_expr, ref_decl) } /// /// ```javascript /// function NAME(PARAMS) { /// return REF.apply(this, arguments); /// } /// ``` fn build_function_forward(&mut self, ref_ident: Ident, name_ident: Option<Ident>) -> FnExpr { let apply = ReturnStmt { span: DUMMY_SP, arg: Some(Box::new(ref_ident.apply( DUMMY_SP, ThisExpr { span: DUMMY_SP }.into(), vec![quote_ident!("arguments").as_arg()], ))), } .into(); FnExpr { ident: name_ident, function: Box::new(Function { params: self.params.take(), span: DUMMY_SP, body: Some(BlockStmt { stmts: vec![apply], ..Default::default() }), is_generator: false, is_async: false, ..Default::default() }), } } } impl From<FnExpr> for FunctionWrapper<Expr> { fn from(mut fn_expr: FnExpr) -> Self { let function_ident = fn_expr.ident.take(); let params = Self::get_params(fn_expr.function.params.iter()); Self { binding_ident: None, function_ident, params, ignore_function_name: false, ignore_function_length: false, function: fn_expr.into(), _type: Default::default(), } } } impl From<ArrowExpr> for FunctionWrapper<Expr> { fn from( ArrowExpr { span, params, body, is_async, is_generator, .. }: ArrowExpr, ) -> Self { let body = Some(match *body { BlockStmtOrExpr::BlockStmt(block) => block, BlockStmtOrExpr::Expr(expr) => BlockStmt { stmts: vec![Stmt::Return(ReturnStmt { span: expr.span(), arg: Some(expr), })], ..Default::default() }, }); let function = Box::new(Function { span, params: params.into_iter().map(Into::into).collect(), body, type_params: None, return_type: None, is_generator, is_async, ..Default::default() }); let fn_expr = FnExpr { ident: None, function, }; Self { binding_ident: None, function_ident: None, ignore_function_name: false, ignore_function_length: false, params: Self::get_params(fn_expr.function.params.iter()), function: fn_expr.into(), _type: Default::default(), } } } #[allow(clippy::from_over_into)] impl Into<Expr> for FunctionWrapper<Expr> { /// If a function has a function name, it may be called recursively. /// We use the named expression to hoist the function name internally /// Therefore, its recursive calls refer to the correct identity. /// /// Else /// if a function has a binding name, it may be called recursively as well. /// But it refer the binding name which exist the outer scope. /// It is safe to using anonymous expression wrapper. /// /// Optimization: /// A function without a name cannot be recursively referenced by Ident. /// It's safe to return the expr without wrapper if the params.len is 0. fn into(mut self) -> Expr { if let Some(name_ident) = self.function_ident.as_ref().cloned() { self.build_named_expression_wrapper(name_ident) } else if (!self.ignore_function_name && self.binding_ident.is_some()) || (!self.ignore_function_length && !self.params.is_empty()) { self.build_anonymous_expression_wrapper() } else { self.function } } } impl From<FnDecl> for FunctionWrapper<FnDecl> { fn from(mut fn_decl: FnDecl) -> Self { let function_ident = Some(fn_decl.ident.take()); let params = Self::get_params(fn_decl.function.params.iter()); Self { binding_ident: None, function_ident, params, ignore_function_name: false, ignore_function_length: false, function: FnExpr { ident: None, function: fn_decl.function, } .into(), _type: Default::default(), } } } /// /// The result of declaration wrapper includes two parts. /// `name_fn` is used to replace the original function. /// `ref_fn` is an extra function called internally by `name_fn`. /// /// ```javascript /// function NAME(PARAMS) { /// return REF.apply(this, arguments); /// } /// function REF() { /// REF = FUNCTION; /// return REF.apply(this, arguments); /// } /// ``` pub struct FnWrapperResult<N, R> { pub name_fn: N, pub ref_fn: R, } impl From<FunctionWrapper<FnDecl>> for FnWrapperResult<FnDecl, FnDecl> { fn from(mut value: FunctionWrapper<FnDecl>) -> Self { let name_ident = value .function_ident .clone() .expect("`FunctionWrapper` converted from `FnDecl` definitely has `Ident`"); let (FnExpr { function, .. }, ref_fn) = value.build_declaration_wrapper(None); FnWrapperResult { name_fn: FnDecl { ident: name_ident, declare: false, function, }, ref_fn, } } } impl From<FunctionWrapper<Expr>> for FnWrapperResult<FnExpr, FnDecl> { fn from(mut value: FunctionWrapper<Expr>) -> Self { let name_ident = value .function_ident .clone() .or_else(|| value.binding_ident.clone()); let (name_fn, ref_fn) = value.build_declaration_wrapper(name_ident); FnWrapperResult { name_fn, ref_fn } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_utils/src/function/mod.rs
Rust
mod fn_env_hoister; mod function_wrapper; pub use fn_env_hoister::*; pub use function_wrapper::*;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_utils/src/ident.rs
Rust
use swc_atoms::Atom; use swc_common::SyntaxContext; use swc_ecma_ast::{unsafe_id_from_ident, BindingIdent, Id, Ident, UnsafeId}; pub trait IdentLike: Sized + Send + Sync + 'static { fn from_ident(i: &Ident) -> Self; fn to_id(&self) -> Id; fn into_id(self) -> Id; } impl IdentLike for Atom { fn from_ident(i: &Ident) -> Self { i.sym.clone() } fn to_id(&self) -> Id { (self.clone(), Default::default()) } fn into_id(self) -> Id { (self, Default::default()) } } impl IdentLike for BindingIdent { fn from_ident(i: &Ident) -> Self { i.clone().into() } fn to_id(&self) -> Id { (self.sym.clone(), self.ctxt) } fn into_id(self) -> Id { self.id.into_id() } } impl IdentLike for (Atom, SyntaxContext) { #[inline] fn from_ident(i: &Ident) -> Self { (i.sym.clone(), i.ctxt) } #[inline] fn to_id(&self) -> Id { (self.0.clone(), self.1) } #[inline] fn into_id(self) -> Id { self } } impl IdentLike for Ident { #[inline] fn from_ident(i: &Ident) -> Self { Ident::new(i.sym.clone(), i.span, i.ctxt) } #[inline] fn to_id(&self) -> Id { (self.sym.clone(), self.ctxt) } #[inline] fn into_id(self) -> Id { (self.sym, self.ctxt) } } impl IdentLike for UnsafeId { fn from_ident(i: &Ident) -> Self { unsafe { unsafe_id_from_ident(i) } } fn to_id(&self) -> Id { unreachable!("UnsafeId.to_id() is not allowed because it is very likely to be unsafe") } fn into_id(self) -> Id { unreachable!("UnsafeId.into_id() is not allowed because it is very likely to be unsafe") } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_utils/src/lib.rs
Rust
#![deny(clippy::all)] #![allow(clippy::boxed_local)] #![allow(clippy::mutable_key_type)] #![allow(clippy::match_like_matches_macro)] #![allow(clippy::vec_box)] #![cfg_attr(not(feature = "concurrent"), allow(unused))] #[doc(hidden)] pub extern crate swc_atoms; #[doc(hidden)] pub extern crate swc_common; #[doc(hidden)] pub extern crate swc_ecma_ast; use std::{borrow::Cow, hash::Hash, num::FpCategory, ops::Add}; use number::ToJsString; use rustc_hash::{FxHashMap, FxHashSet}; use swc_atoms::Atom; use swc_common::{util::take::Take, Mark, Span, Spanned, SyntaxContext, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_visit::{ noop_visit_mut_type, noop_visit_type, visit_mut_obj_and_computed, visit_obj_and_computed, Visit, VisitMut, VisitMutWith, VisitWith, }; use tracing::trace; #[allow(deprecated)] pub use self::{ factory::{ExprFactory, FunctionFactory, IntoIndirectCall}, value::{ Merge, Type::{ self, Bool as BoolType, Null as NullType, Num as NumberType, Obj as ObjectType, Str as StringType, Symbol as SymbolType, Undefined as UndefinedType, }, Value::{self, Known, Unknown}, }, Purity::{MayBeImpure, Pure}, }; use crate::ident::IdentLike; #[macro_use] mod macros; pub mod constructor; mod factory; pub mod function; pub mod ident; pub mod parallel; mod value; pub mod var; mod node_ignore_span; pub mod number; pub mod stack_size; pub use node_ignore_span::NodeIgnoringSpan; // TODO: remove pub struct ThisVisitor { found: bool, } impl Visit for ThisVisitor { noop_visit_type!(); /// Don't recurse into constructor fn visit_constructor(&mut self, _: &Constructor) {} /// Don't recurse into fn fn visit_fn_decl(&mut self, _: &FnDecl) {} /// Don't recurse into fn fn visit_fn_expr(&mut self, _: &FnExpr) {} /// Don't recurse into fn fn visit_function(&mut self, _: &Function) {} /// Don't recurse into fn fn visit_getter_prop(&mut self, n: &GetterProp) { n.key.visit_with(self); } /// Don't recurse into fn fn visit_method_prop(&mut self, n: &MethodProp) { n.key.visit_with(self); n.function.visit_with(self); } /// Don't recurse into fn fn visit_setter_prop(&mut self, n: &SetterProp) { n.key.visit_with(self); n.param.visit_with(self); } fn visit_this_expr(&mut self, _: &ThisExpr) { self.found = true; } } /// This does not recurse into a function if `this` is changed by it. /// /// e.g. /// /// - The body of an arrow expression is visited. /// - The body of a function expression is **not** visited. pub fn contains_this_expr<N>(body: &N) -> bool where N: VisitWith<ThisVisitor>, { let mut visitor = ThisVisitor { found: false }; body.visit_with(&mut visitor); visitor.found } pub fn contains_ident_ref<'a, N>(body: &N, ident: &'a Id) -> bool where N: VisitWith<IdentRefFinder<'a>>, { let mut visitor = IdentRefFinder { found: false, ident, }; body.visit_with(&mut visitor); visitor.found } pub struct IdentRefFinder<'a> { ident: &'a Id, found: bool, } impl Visit for IdentRefFinder<'_> { noop_visit_type!(); fn visit_expr(&mut self, e: &Expr) { e.visit_children_with(self); match *e { Expr::Ident(ref i) if i.sym == self.ident.0 && i.ctxt == self.ident.1 => { self.found = true; } _ => {} } } } // TODO: remove pub fn contains_arguments<N>(body: &N) -> bool where N: VisitWith<ArgumentsFinder>, { let mut visitor = ArgumentsFinder { found: false }; body.visit_with(&mut visitor); visitor.found } pub struct ArgumentsFinder { found: bool, } impl Visit for ArgumentsFinder { noop_visit_type!(); /// Don't recurse into constructor fn visit_constructor(&mut self, _: &Constructor) {} fn visit_expr(&mut self, e: &Expr) { e.visit_children_with(self); if e.is_ident_ref_to("arguments") { self.found = true; } } /// Don't recurse into fn fn visit_function(&mut self, _: &Function) {} fn visit_prop(&mut self, n: &Prop) { n.visit_children_with(self); if let Prop::Shorthand(i) = n { if &*i.sym == "arguments" { self.found = true; } } } } pub trait StmtOrModuleItem: Send + Sync + Sized { fn into_stmt(self) -> Result<Stmt, ModuleDecl>; fn as_stmt(&self) -> Result<&Stmt, &ModuleDecl>; fn as_stmt_mut(&mut self) -> Result<&mut Stmt, &mut ModuleDecl>; fn from_stmt(stmt: Stmt) -> Self; fn try_from_module_decl(decl: ModuleDecl) -> Result<Self, ModuleDecl>; } impl StmtOrModuleItem for Stmt { #[inline] fn into_stmt(self) -> Result<Stmt, ModuleDecl> { Ok(self) } #[inline] fn as_stmt(&self) -> Result<&Stmt, &ModuleDecl> { Ok(self) } #[inline] fn as_stmt_mut(&mut self) -> Result<&mut Stmt, &mut ModuleDecl> { Ok(self) } #[inline] fn from_stmt(stmt: Stmt) -> Self { stmt } #[inline] fn try_from_module_decl(decl: ModuleDecl) -> Result<Self, ModuleDecl> { Err(decl) } } impl StmtOrModuleItem for ModuleItem { #[inline] fn into_stmt(self) -> Result<Stmt, ModuleDecl> { match self { ModuleItem::ModuleDecl(v) => Err(v), ModuleItem::Stmt(v) => Ok(v), } } #[inline] fn as_stmt(&self) -> Result<&Stmt, &ModuleDecl> { match self { ModuleItem::ModuleDecl(v) => Err(v), ModuleItem::Stmt(v) => Ok(v), } } #[inline] fn as_stmt_mut(&mut self) -> Result<&mut Stmt, &mut ModuleDecl> { match self { ModuleItem::ModuleDecl(v) => Err(v), ModuleItem::Stmt(v) => Ok(v), } } #[inline] fn from_stmt(stmt: Stmt) -> Self { stmt.into() } #[inline] fn try_from_module_decl(decl: ModuleDecl) -> Result<Self, ModuleDecl> { Ok(decl.into()) } } pub trait ModuleItemLike: StmtLike { fn try_into_module_decl(self) -> Result<ModuleDecl, Self> { Err(self) } fn try_from_module_decl(decl: ModuleDecl) -> Result<Self, ModuleDecl> { Err(decl) } } pub trait StmtLike: Sized + 'static + Send + Sync + From<Stmt> { fn try_into_stmt(self) -> Result<Stmt, Self>; fn as_stmt(&self) -> Option<&Stmt>; fn as_stmt_mut(&mut self) -> Option<&mut Stmt>; } impl ModuleItemLike for Stmt {} impl StmtLike for Stmt { #[inline] fn try_into_stmt(self) -> Result<Stmt, Self> { Ok(self) } #[inline] fn as_stmt(&self) -> Option<&Stmt> { Some(self) } #[inline] fn as_stmt_mut(&mut self) -> Option<&mut Stmt> { Some(self) } } impl ModuleItemLike for ModuleItem { #[inline] fn try_into_module_decl(self) -> Result<ModuleDecl, Self> { match self { ModuleItem::ModuleDecl(decl) => Ok(decl), _ => Err(self), } } #[inline] fn try_from_module_decl(decl: ModuleDecl) -> Result<Self, ModuleDecl> { Ok(decl.into()) } } impl StmtLike for ModuleItem { #[inline] fn try_into_stmt(self) -> Result<Stmt, Self> { match self { ModuleItem::Stmt(stmt) => Ok(stmt), _ => Err(self), } } #[inline] fn as_stmt(&self) -> Option<&Stmt> { match self { ModuleItem::Stmt(stmt) => Some(stmt), _ => None, } } #[inline] fn as_stmt_mut(&mut self) -> Option<&mut Stmt> { match &mut *self { ModuleItem::Stmt(stmt) => Some(stmt), _ => None, } } } /// Prepends statements after directive statements. pub trait StmtLikeInjector<S> where S: StmtLike, { fn prepend_stmt(&mut self, insert_with: S); fn prepend_stmts<I>(&mut self, insert_with: I) where I: IntoIterator<Item = S>; } impl<S> StmtLikeInjector<S> for Vec<S> where S: StmtLike, { /// Note: If there is no directive, use `insert` instead. fn prepend_stmt(&mut self, insert_with: S) { let directive_pos = self .iter() .position(|stmt| !stmt.as_stmt().map_or(false, is_maybe_branch_directive)) .unwrap_or(self.len()); self.insert(directive_pos, insert_with); } /// Note: If there is no directive, use `splice` instead. fn prepend_stmts<I>(&mut self, insert_with: I) where I: IntoIterator<Item = S>, { let directive_pos = self .iter() .position(|stmt| !stmt.as_stmt().map_or(false, is_maybe_branch_directive)) .unwrap_or(self.len()); self.splice(directive_pos..directive_pos, insert_with); } } pub type BoolValue = Value<bool>; pub trait IsEmpty { fn is_empty(&self) -> bool; } impl IsEmpty for BlockStmt { fn is_empty(&self) -> bool { self.stmts.is_empty() } } impl IsEmpty for CatchClause { fn is_empty(&self) -> bool { self.body.stmts.is_empty() } } impl IsEmpty for Stmt { fn is_empty(&self) -> bool { match *self { Stmt::Empty(_) => true, Stmt::Block(ref b) => b.is_empty(), _ => false, } } } impl<T: IsEmpty> IsEmpty for Option<T> { #[inline] fn is_empty(&self) -> bool { match *self { Some(ref node) => node.is_empty(), None => true, } } } impl<T: IsEmpty> IsEmpty for Box<T> { #[inline] fn is_empty(&self) -> bool { <T as IsEmpty>::is_empty(self) } } impl<T> IsEmpty for Vec<T> { #[inline] fn is_empty(&self) -> bool { self.is_empty() } } /// Extracts hoisted variables pub fn extract_var_ids<T: VisitWith<Hoister>>(node: &T) -> Vec<Ident> { let mut v = Hoister { vars: Vec::new() }; node.visit_with(&mut v); v.vars } pub trait StmtExt { fn as_stmt(&self) -> &Stmt; /// Extracts hoisted variables fn extract_var_ids(&self) -> Vec<Ident> { extract_var_ids(self.as_stmt()) } fn extract_var_ids_as_var(&self) -> Option<VarDecl> { let ids = self.extract_var_ids(); if ids.is_empty() { return None; } Some(VarDecl { kind: VarDeclKind::Var, decls: ids .into_iter() .map(|i| VarDeclarator { span: i.span, name: i.into(), init: None, definite: false, }) .collect(), ..Default::default() }) } /// stmts contain top level return/break/continue/throw fn terminates(&self) -> bool { fn terminates(stmt: &Stmt) -> bool { match stmt { Stmt::Break(_) | Stmt::Continue(_) | Stmt::Throw(_) | Stmt::Return(_) => true, Stmt::Block(block) => block.stmts.iter().rev().any(|s| s.terminates()), Stmt::If(IfStmt { cons, alt: Some(alt), .. }) => cons.terminates() && alt.terminates(), _ => false, } } terminates(self.as_stmt()) } fn may_have_side_effects(&self, ctx: ExprCtx) -> bool { fn may_have_side_effects(stmt: &Stmt, ctx: ExprCtx) -> bool { match stmt { Stmt::Block(block_stmt) => block_stmt .stmts .iter() .any(|stmt| stmt.may_have_side_effects(ctx)), Stmt::Empty(_) => false, Stmt::Labeled(labeled_stmt) => labeled_stmt.body.may_have_side_effects(ctx), Stmt::If(if_stmt) => { if_stmt.test.may_have_side_effects(ctx) || if_stmt.cons.may_have_side_effects(ctx) || if_stmt .alt .as_ref() .map_or(false, |stmt| stmt.may_have_side_effects(ctx)) } Stmt::Switch(switch_stmt) => { switch_stmt.discriminant.may_have_side_effects(ctx) || switch_stmt.cases.iter().any(|case| { case.test .as_ref() .map_or(false, |expr| expr.may_have_side_effects(ctx)) || case.cons.iter().any(|con| con.may_have_side_effects(ctx)) }) } Stmt::Try(try_stmt) => { try_stmt .block .stmts .iter() .any(|stmt| stmt.may_have_side_effects(ctx)) || try_stmt.handler.as_ref().map_or(false, |handler| { handler .body .stmts .iter() .any(|stmt| stmt.may_have_side_effects(ctx)) }) || try_stmt.finalizer.as_ref().map_or(false, |finalizer| { finalizer .stmts .iter() .any(|stmt| stmt.may_have_side_effects(ctx)) }) } Stmt::Decl(decl) => match decl { Decl::Class(class_decl) => class_has_side_effect(ctx, &class_decl.class), Decl::Fn(_) => !ctx.in_strict, Decl::Var(var_decl) => var_decl.kind == VarDeclKind::Var, _ => false, }, Stmt::Expr(expr_stmt) => expr_stmt.expr.may_have_side_effects(ctx), _ => true, } } may_have_side_effects(self.as_stmt(), ctx) } } impl StmtExt for Stmt { fn as_stmt(&self) -> &Stmt { self } } impl StmtExt for Box<Stmt> { fn as_stmt(&self) -> &Stmt { self } } pub struct Hoister { vars: Vec<Ident>, } impl Visit for Hoister { noop_visit_type!(); fn visit_assign_expr(&mut self, node: &AssignExpr) { node.right.visit_children_with(self); } fn visit_assign_pat_prop(&mut self, node: &AssignPatProp) { node.value.visit_with(self); self.vars.push(node.key.clone().into()); } fn visit_fn_decl(&mut self, f: &FnDecl) { self.vars.push(f.ident.clone()); } fn visit_pat(&mut self, p: &Pat) { p.visit_children_with(self); if let Pat::Ident(ref i) = *p { self.vars.push(i.clone().into()) } } fn visit_var_decl(&mut self, v: &VarDecl) { if v.kind != VarDeclKind::Var { return; } v.visit_children_with(self) } fn visit_fn_expr(&mut self, _n: &FnExpr) {} } #[derive(Debug, Clone, Copy)] pub struct ExprCtx { /// This [SyntaxContext] should be applied only to unresolved references. /// /// In other words, this should be applied to identifier references to /// global objects like `Object` or `Math`, and when those are not shadowed /// by a local declaration. pub unresolved_ctxt: SyntaxContext, /// True for argument of `typeof`. pub is_unresolved_ref_safe: bool, /// True if we are in the strict mode. This will be set to `true` for /// statements **after** `'use strict'` pub in_strict: bool, /// Remaining depth of the current expression. If this is 0, it means the /// function should not operate and return the safe value. /// /// Default value is `4` pub remaining_depth: u32, } /// Extension methods for [Expr]. pub trait ExprExt { fn as_expr(&self) -> &Expr; /// Returns true if this is an immutable value. #[inline(always)] fn is_immutable_value(&self) -> bool { is_immutable_value(self.as_expr()) } #[inline(always)] fn is_number(&self) -> bool { is_number(self.as_expr()) } // TODO: remove this after a proper evaluator #[inline(always)] fn is_str(&self) -> bool { is_str(self.as_expr()) } #[inline(always)] fn is_array_lit(&self) -> bool { is_array_lit(self.as_expr()) } /// Checks if `self` is `NaN`. #[inline(always)] fn is_nan(&self) -> bool { is_nan(self.as_expr()) } #[inline(always)] fn is_undefined(&self, ctx: ExprCtx) -> bool { is_undefined(self.as_expr(), ctx) } #[inline(always)] fn is_void(&self) -> bool { is_void(self.as_expr()) } /// Returns `true` if `id` references a global object. #[inline(always)] fn is_global_ref_to(&self, ctx: ExprCtx, id: &str) -> bool { is_global_ref_to(self.as_expr(), ctx, id) } /// Returns `true` if `id` references a global object. #[inline(always)] fn is_one_of_global_ref_to(&self, ctx: ExprCtx, ids: &[&str]) -> bool { is_one_of_global_ref_to(self.as_expr(), ctx, ids) } /// Get bool value of `self` if it does not have any side effects. #[inline(always)] fn as_pure_bool(&self, ctx: ExprCtx) -> BoolValue { as_pure_bool(self.as_expr(), ctx) } /// /// This method emulates the `Boolean()` JavaScript cast function. ///Note: unlike getPureBooleanValue this function does not return `None` ///for expressions with side-effects. #[inline(always)] fn cast_to_bool(&self, ctx: ExprCtx) -> (Purity, BoolValue) { cast_to_bool(self.as_expr(), ctx) } #[inline(always)] fn cast_to_number(&self, ctx: ExprCtx) -> (Purity, Value<f64>) { cast_to_number(self.as_expr(), ctx) } /// Emulates javascript Number() cast function. /// /// Note: This method returns [Known] only if it's pure. #[inline(always)] fn as_pure_number(&self, ctx: ExprCtx) -> Value<f64> { as_pure_number(self.as_expr(), ctx) } /// Returns Known only if it's pure. #[inline(always)] fn as_pure_string(&self, ctx: ExprCtx) -> Value<Cow<'_, str>> { as_pure_string(self.as_expr(), ctx) } /// Apply the supplied predicate against all possible result Nodes of the /// expression. #[inline(always)] fn get_type(&self, ctx: ExprCtx) -> Value<Type> { get_type(self.as_expr(), ctx) } #[inline(always)] fn is_pure_callee(&self, ctx: ExprCtx) -> bool { is_pure_callee(self.as_expr(), ctx) } #[inline(always)] fn may_have_side_effects(&self, ctx: ExprCtx) -> bool { may_have_side_effects(self.as_expr(), ctx) } } pub fn class_has_side_effect(expr_ctx: ExprCtx, c: &Class) -> bool { if let Some(e) = &c.super_class { if e.may_have_side_effects(expr_ctx) { return true; } } for m in &c.body { match m { ClassMember::Method(p) => { if let PropName::Computed(key) = &p.key { if key.expr.may_have_side_effects(expr_ctx) { return true; } } } ClassMember::ClassProp(p) => { if let PropName::Computed(key) = &p.key { if key.expr.may_have_side_effects(expr_ctx) { return true; } } if let Some(v) = &p.value { if v.may_have_side_effects(expr_ctx) { return true; } } } ClassMember::PrivateProp(p) => { if let Some(v) = &p.value { if v.may_have_side_effects(expr_ctx) { return true; } } } ClassMember::StaticBlock(s) => { if s.body .stmts .iter() .any(|stmt| stmt.may_have_side_effects(expr_ctx)) { return true; } } _ => {} } } false } fn and(lt: Value<Type>, rt: Value<Type>) -> Value<Type> { if lt == rt { return lt; } Unknown } /// Return if the node is possibly a string. fn may_be_str(ty: Value<Type>) -> bool { match ty { Known(BoolType) | Known(NullType) | Known(NumberType) | Known(UndefinedType) => false, Known(ObjectType) | Known(StringType) | Unknown => true, // TODO: Check if this is correct Known(SymbolType) => true, } } pub fn num_from_str(s: &str) -> Value<f64> { if s.contains('\u{000b}') { return Unknown; } let s = s.trim(); if s.is_empty() { return Known(0.0); } if s.len() >= 2 { match &s.as_bytes()[..2] { b"0x" | b"0X" => { return match u64::from_str_radix(&s[2..], 16) { Ok(n) => Known(n as f64), Err(_) => Known(f64::NAN), } } b"0o" | b"0O" => { return match u64::from_str_radix(&s[2..], 8) { Ok(n) => Known(n as f64), Err(_) => Known(f64::NAN), }; } b"0b" | b"0B" => { return match u64::from_str_radix(&s[2..], 2) { Ok(n) => Known(n as f64), Err(_) => Known(f64::NAN), }; } _ => {} } } if (s.starts_with('-') || s.starts_with('+')) && (s[1..].starts_with("0x") || s[1..].starts_with("0X")) { // hex numbers with explicit signs vary between browsers. return Unknown; } // Firefox and IE treat the "Infinity" differently. Firefox is case // insensitive, but IE treats "infinity" as NaN. So leave it alone. match s { "infinity" | "+infinity" | "-infinity" => return Unknown, _ => {} } Known(s.parse().ok().unwrap_or(f64::NAN)) } impl ExprExt for Box<Expr> { #[inline(always)] fn as_expr(&self) -> &Expr { self } } impl ExprExt for Expr { #[inline(always)] fn as_expr(&self) -> &Expr { self } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Purity { /// May have some side effects. MayBeImpure, /// Does not have any side effect. Pure, } impl Purity { /// Returns true if it's pure. pub fn is_pure(self) -> bool { self == Pure } } impl Add for Purity { type Output = Self; fn add(self, rhs: Self) -> Self { match (self, rhs) { (Pure, Pure) => Pure, _ => MayBeImpure, } } } /// Cast to javascript's int32 pub fn to_int32(d: f64) -> i32 { let id = d as i32; if id as f64 == d { // This covers -0.0 as well return id; } if d.is_nan() || d.is_infinite() { return 0; } let d = if d >= 0.0 { d.floor() } else { d.ceil() }; const TWO32: f64 = 4_294_967_296.0; let d = d % TWO32; // (double)(long)d == d should hold here let l = d as i64; // returning (int)d does not work as d can be outside int range // but the result must always be 32 lower bits of l l as i32 } // pub fn to_u32(_d: f64) -> u32 { // // if (Double.isNaN(d) || Double.isInfinite(d) || d == 0) { // // return 0; // // } // // d = Math.signum(d) * Math.floor(Math.abs(d)); // // double two32 = 4294967296.0; // // // this ensures that d is positive // // d = ((d % two32) + two32) % two32; // // // (double)(long)d == d should hold here // // long l = (long) d; // // // returning (int)d does not work as d can be outside int range // // // but the result must always be 32 lower bits of l // // return (int) l; // unimplemented!("to_u32") // } pub fn has_rest_pat<T: VisitWith<RestPatVisitor>>(node: &T) -> bool { let mut v = RestPatVisitor { found: false }; node.visit_with(&mut v); v.found } pub struct RestPatVisitor { found: bool, } impl Visit for RestPatVisitor { noop_visit_type!(); fn visit_rest_pat(&mut self, _: &RestPat) { self.found = true; } } pub fn is_literal<T>(node: &T) -> bool where T: VisitWith<LiteralVisitor>, { let (v, _) = calc_literal_cost(node, true); v } #[inline(never)] pub fn calc_literal_cost<T>(e: &T, allow_non_json_value: bool) -> (bool, usize) where T: VisitWith<LiteralVisitor>, { let mut v = LiteralVisitor { is_lit: true, cost: 0, allow_non_json_value, }; e.visit_with(&mut v); (v.is_lit, v.cost) } pub struct LiteralVisitor { is_lit: bool, cost: usize, allow_non_json_value: bool, } impl Visit for LiteralVisitor { noop_visit_type!(); fn visit_array_lit(&mut self, e: &ArrayLit) { if !self.is_lit { return; } self.cost += 2 + e.elems.len(); e.visit_children_with(self); for elem in &e.elems { if !self.allow_non_json_value && elem.is_none() { self.is_lit = false; } } } fn visit_arrow_expr(&mut self, _: &ArrowExpr) { self.is_lit = false } fn visit_assign_expr(&mut self, _: &AssignExpr) { self.is_lit = false; } fn visit_await_expr(&mut self, _: &AwaitExpr) { self.is_lit = false } fn visit_bin_expr(&mut self, _: &BinExpr) { self.is_lit = false } fn visit_call_expr(&mut self, _: &CallExpr) { self.is_lit = false } fn visit_class_expr(&mut self, _: &ClassExpr) { self.is_lit = false } fn visit_cond_expr(&mut self, _: &CondExpr) { self.is_lit = false; } fn visit_expr(&mut self, e: &Expr) { if !self.is_lit { return; } match *e { Expr::Ident(..) | Expr::Lit(Lit::Regex(..)) => self.is_lit = false, Expr::Tpl(ref tpl) if !tpl.exprs.is_empty() => self.is_lit = false, _ => e.visit_children_with(self), } } fn visit_fn_expr(&mut self, _: &FnExpr) { self.is_lit = false; } fn visit_invalid(&mut self, _: &Invalid) { self.is_lit = false; } fn visit_member_expr(&mut self, _: &MemberExpr) { self.is_lit = false; } fn visit_meta_prop_expr(&mut self, _: &MetaPropExpr) { self.is_lit = false } fn visit_new_expr(&mut self, _: &NewExpr) { self.is_lit = false } fn visit_number(&mut self, node: &Number) { if !self.allow_non_json_value && node.value.is_infinite() { self.is_lit = false; } } fn visit_opt_chain_expr(&mut self, _: &OptChainExpr) { self.is_lit = false } fn visit_private_name(&mut self, _: &PrivateName) { self.is_lit = false } fn visit_prop(&mut self, p: &Prop) { if !self.is_lit { return; } p.visit_children_with(self); match p { Prop::KeyValue(..) => { self.cost += 1; } _ => self.is_lit = false, } } fn visit_prop_name(&mut self, node: &PropName) { if !self.is_lit { return; } node.visit_children_with(self); match node { PropName::Str(ref s) => self.cost += 2 + s.value.len(), PropName::Ident(ref id) => self.cost += 2 + id.sym.len(), PropName::Num(..) => { // TODO: Count digits self.cost += 5; } PropName::BigInt(_) => self.is_lit = false, PropName::Computed(..) => self.is_lit = false, } } fn visit_seq_expr(&mut self, _: &SeqExpr) { self.is_lit = false } fn visit_spread_element(&mut self, _: &SpreadElement) { self.is_lit = false; } fn visit_tagged_tpl(&mut self, _: &TaggedTpl) { self.is_lit = false } fn visit_this_expr(&mut self, _: &ThisExpr) { self.is_lit = false; } fn visit_ts_const_assertion(&mut self, _: &TsConstAssertion) { self.is_lit = false } fn visit_ts_non_null_expr(&mut self, _: &TsNonNullExpr) { self.is_lit = false } fn visit_unary_expr(&mut self, _: &UnaryExpr) { self.is_lit = false; } fn visit_update_expr(&mut self, _: &UpdateExpr) { self.is_lit = false; } fn visit_yield_expr(&mut self, _: &YieldExpr) { self.is_lit = false } } pub fn is_simple_pure_expr(expr: &Expr, pure_getters: bool) -> bool { match expr { Expr::Ident(..) | Expr::This(..) | Expr::Lit(..) => true, Expr::Unary(UnaryExpr { op: op!("void") | op!("!"), arg, .. }) => is_simple_pure_expr(arg, pure_getters), Expr::Member(m) if pure_getters => is_simple_pure_member_expr(m, pure_getters), _ => false, } } pub fn is_simple_pure_member_expr(m: &MemberExpr, pure_getters: bool) -> bool { match &m.prop { MemberProp::Ident(..) | MemberProp::PrivateName(..) => { is_simple_pure_expr(&m.obj, pure_getters) } MemberProp::Computed(c) => { is_simple_pure_expr(&c.expr, pure_getters) && is_simple_pure_expr(&m.obj, pure_getters) } } } fn sym_for_expr(expr: &Expr) -> Option<String> { match expr { Expr::Lit(Lit::Str(s)) => Some(s.value.to_string()), Expr::This(_) => Some("this".to_string()), Expr::Ident(ident) | Expr::Fn(FnExpr { ident: Some(ident), .. }) | Expr::Class(ClassExpr { ident: Some(ident), .. }) => Some(ident.sym.to_string()), Expr::OptChain(OptChainExpr { base, .. }) => match &**base { OptChainBase::Call(OptCall { callee: expr, .. }) => sym_for_expr(expr), OptChainBase::Member(MemberExpr { prop: MemberProp::Ident(ident), obj, .. }) => Some(format!( "{}_{}", sym_for_expr(obj).unwrap_or_default(), ident.sym )), OptChainBase::Member(MemberExpr { prop: MemberProp::Computed(ComputedPropName { expr, .. }), obj, .. }) => Some(format!( "{}_{}", sym_for_expr(obj).unwrap_or_default(), sym_for_expr(expr).unwrap_or_default() )), _ => None, }, Expr::Call(CallExpr { callee: Callee::Expr(expr), .. }) => sym_for_expr(expr), Expr::SuperProp(SuperPropExpr { prop: SuperProp::Ident(ident), .. }) => Some(format!("super_{}", ident.sym)), Expr::SuperProp(SuperPropExpr { prop: SuperProp::Computed(ComputedPropName { expr, .. }), .. }) => Some(format!("super_{}", sym_for_expr(expr).unwrap_or_default())), Expr::Member(MemberExpr { prop: MemberProp::Ident(ident), obj, .. }) => Some(format!( "{}_{}", sym_for_expr(obj).unwrap_or_default(), ident.sym )), Expr::Member(MemberExpr { prop: MemberProp::Computed(ComputedPropName { expr, .. }), obj, .. }) => Some(format!( "{}_{}", sym_for_expr(obj).unwrap_or_default(), sym_for_expr(expr).unwrap_or_default() )), _ => None, } } /// Used to determine super_class_ident pub fn alias_ident_for(expr: &Expr, default: &str) -> Ident { let ctxt = SyntaxContext::empty().apply_mark(Mark::fresh(Mark::root())); let span = expr.span(); let mut sym = sym_for_expr(expr).unwrap_or_else(|| default.to_string()); if let Err(s) = Ident::verify_symbol(&sym) { sym = s; } if !sym.starts_with('_') { sym = format!("_{}", sym) } quote_ident!(ctxt, span, sym) } /// Used to determine super_class_ident pub fn alias_ident_for_simple_assign_tatget(expr: &SimpleAssignTarget, default: &str) -> Ident { let ctxt = SyntaxContext::empty().apply_mark(Mark::fresh(Mark::root())); let span = expr.span(); let mut sym = match expr { SimpleAssignTarget::Ident(i) => Some(i.sym.to_string()), SimpleAssignTarget::SuperProp(SuperPropExpr { prop: SuperProp::Ident(ident), .. }) => Some(format!("super_{}", ident.sym)), SimpleAssignTarget::SuperProp(SuperPropExpr { prop: SuperProp::Computed(ComputedPropName { expr, .. }), .. }) => Some(format!("super_{}", sym_for_expr(expr).unwrap_or_default())), SimpleAssignTarget::Member(MemberExpr { prop: MemberProp::Ident(ident), obj, .. }) => Some(format!( "{}_{}", sym_for_expr(obj).unwrap_or_default(), ident.sym )), SimpleAssignTarget::Member(MemberExpr { prop: MemberProp::Computed(ComputedPropName { expr, .. }), obj, .. }) => Some(format!( "{}_{}", sym_for_expr(obj).unwrap_or_default(), sym_for_expr(expr).unwrap_or_default() )), _ => None, } .unwrap_or_else(|| default.to_string()); if let Err(s) = Ident::verify_symbol(&sym) { sym = s; } if !sym.starts_with('_') { sym = format!("_{}", sym) } quote_ident!(ctxt, span, sym) } /// Returns `(ident, aliased)` pub fn alias_if_required(expr: &Expr, default: &str) -> (Ident, bool) { if let Expr::Ident(ref i) = *expr { return (Ident::new(i.sym.clone(), i.span, i.ctxt), false); } (alias_ident_for(expr, default), true) } pub fn prop_name_to_expr(p: PropName) -> Expr { match p { PropName::Ident(i) => i.into(), PropName::Str(s) => Lit::Str(s).into(), PropName::Num(n) => Lit::Num(n).into(), PropName::BigInt(b) => Lit::BigInt(b).into(), PropName::Computed(c) => *c.expr, } } /// Similar to `prop_name_to_expr`, but used for value position. /// /// e.g. value from `{ key: value }` pub fn prop_name_to_expr_value(p: PropName) -> Expr { match p { PropName::Ident(i) => Lit::Str(Str { span: i.span, raw: None, value: i.sym, }) .into(), PropName::Str(s) => Lit::Str(s).into(), PropName::Num(n) => Lit::Num(n).into(), PropName::BigInt(b) => Lit::BigInt(b).into(), PropName::Computed(c) => *c.expr, } } pub fn prop_name_to_member_prop(prop_name: PropName) -> MemberProp { match prop_name { PropName::Ident(i) => MemberProp::Ident(i), PropName::Str(s) => MemberProp::Computed(ComputedPropName { span: DUMMY_SP, expr: s.into(), }), PropName::Num(n) => MemberProp::Computed(ComputedPropName { span: DUMMY_SP, expr: n.into(), }), PropName::Computed(c) => MemberProp::Computed(c), PropName::BigInt(b) => MemberProp::Computed(ComputedPropName { span: DUMMY_SP, expr: b.into(), }), } } /// `super_call_span` should be the span of the class definition /// Use value of [`Class::span`]. pub fn default_constructor_with_span(has_super: bool, super_call_span: Span) -> Constructor { trace!(has_super = has_super, "Creating a default constructor"); let super_call_span = super_call_span.with_hi(super_call_span.lo); Constructor { span: DUMMY_SP, key: PropName::Ident("constructor".into()), is_optional: false, params: if has_super { vec![ParamOrTsParamProp::Param(Param { span: DUMMY_SP, decorators: Vec::new(), pat: Pat::Rest(RestPat { span: DUMMY_SP, dot3_token: DUMMY_SP, arg: Box::new(Pat::Ident(quote_ident!("args").into())), type_ann: Default::default(), }), })] } else { Vec::new() }, body: Some(BlockStmt { stmts: if has_super { vec![CallExpr { span: super_call_span, callee: Callee::Super(Super { span: DUMMY_SP }), args: vec![ExprOrSpread { spread: Some(DUMMY_SP), expr: Box::new(Expr::Ident(quote_ident!("args").into())), }], ..Default::default() } .into_stmt()] } else { Vec::new() }, ..Default::default() }), ..Default::default() } } /// Check if `e` is `...arguments` pub fn is_rest_arguments(e: &ExprOrSpread) -> bool { if e.spread.is_none() { return false; } e.expr.is_ident_ref_to("arguments") } pub fn opt_chain_test( left: Box<Expr>, right: Box<Expr>, span: Span, no_document_all: bool, ) -> Expr { if no_document_all { BinExpr { span, left, op: op!("=="), right: Lit::Null(Null { span: DUMMY_SP }).into(), } .into() } else { BinExpr { span, left: BinExpr { span: DUMMY_SP, left, op: op!("==="), right: Box::new(Expr::Lit(Lit::Null(Null { span: DUMMY_SP }))), } .into(), op: op!("||"), right: BinExpr { span: DUMMY_SP, left: right, op: op!("==="), right: Expr::undefined(DUMMY_SP), } .into(), } .into() } } /// inject `branch` after directives #[inline] pub fn prepend_stmt<T: StmtLike>(stmts: &mut Vec<T>, stmt: T) { stmts.prepend_stmt(stmt); } /// If the stmt is maybe a directive like `"use strict";` pub fn is_maybe_branch_directive(stmt: &Stmt) -> bool { match stmt { Stmt::Expr(ExprStmt { ref expr, .. }) if matches!(&**expr, Expr::Lit(Lit::Str(..))) => true, _ => false, } } /// inject `stmts` after directives #[inline] pub fn prepend_stmts<T: StmtLike>(to: &mut Vec<T>, stmts: impl ExactSizeIterator<Item = T>) { to.prepend_stmts(stmts); } pub trait IsDirective { fn as_ref(&self) -> Option<&Stmt>; fn directive_continue(&self) -> bool { self.as_ref().map_or(false, Stmt::can_precede_directive) } fn is_use_strict(&self) -> bool { self.as_ref().map_or(false, Stmt::is_use_strict) } } impl IsDirective for Stmt { fn as_ref(&self) -> Option<&Stmt> { Some(self) } } impl IsDirective for ModuleItem { fn as_ref(&self) -> Option<&Stmt> { self.as_stmt() } } impl IsDirective for &ModuleItem { fn as_ref(&self) -> Option<&Stmt> { self.as_stmt() } } /// Finds all **binding** idents of variables. pub struct DestructuringFinder<I: IdentLike> { pub found: Vec<I>, } /// Finds all **binding** idents of `node`. /// /// If you want to avoid allocation, use [`for_each_binding_ident`] instead. pub fn find_pat_ids<T, I: IdentLike>(node: &T) -> Vec<I> where T: VisitWith<DestructuringFinder<I>>, { let mut v = DestructuringFinder { found: Vec::new() }; node.visit_with(&mut v); v.found } impl<I: IdentLike> Visit for DestructuringFinder<I> { /// No-op (we don't care about expressions) fn visit_expr(&mut self, _: &Expr) {} fn visit_ident(&mut self, i: &Ident) { self.found.push(I::from_ident(i)); } fn visit_jsx_member_expr(&mut self, n: &JSXMemberExpr) { n.obj.visit_with(self); } /// No-op (we don't care about expressions) fn visit_prop_name(&mut self, _: &PropName) {} fn visit_ts_type(&mut self, _: &TsType) {} } /// Finds all **binding** idents of variables. pub struct BindingIdentifierVisitor<F> where F: for<'a> FnMut(&'a BindingIdent), { op: F, } /// Finds all **binding** idents of `node`. **Any nested identifiers in /// expressions are ignored**. pub fn for_each_binding_ident<T, F>(node: &T, op: F) where T: VisitWith<BindingIdentifierVisitor<F>>, F: for<'a> FnMut(&'a BindingIdent), { let mut v = BindingIdentifierVisitor { op }; node.visit_with(&mut v); } impl<F> Visit for BindingIdentifierVisitor<F> where F: for<'a> FnMut(&'a BindingIdent), { noop_visit_type!(); /// No-op (we don't care about expressions) fn visit_expr(&mut self, _: &Expr) {} fn visit_binding_ident(&mut self, i: &BindingIdent) { (self.op)(i); } } pub fn is_valid_ident(s: &Atom) -> bool { if s.len() == 0 { return false; } Ident::verify_symbol(s).is_ok() } pub fn is_valid_prop_ident(s: &str) -> bool { s.starts_with(Ident::is_valid_start) && s.chars().all(Ident::is_valid_continue) } pub fn drop_span<T>(mut t: T) -> T where T: VisitMutWith<DropSpan>, { t.visit_mut_with(&mut DropSpan {}); t } pub struct DropSpan; impl Pass for DropSpan { fn process(&mut self, program: &mut Program) { program.visit_mut_with(self); } } impl VisitMut for DropSpan { fn visit_mut_span(&mut self, span: &mut Span) { *span = DUMMY_SP; } } /// Finds usage of `ident` pub struct IdentUsageFinder<'a> { ident: &'a Id, found: bool, } impl Visit for IdentUsageFinder<'_> { noop_visit_type!(); visit_obj_and_computed!(); fn visit_ident(&mut self, i: &Ident) { if i.ctxt == self.ident.1 && i.sym == self.ident.0 { self.found = true; } } } impl<'a> IdentUsageFinder<'a> { pub fn find<N>(ident: &'a Id, node: &N) -> bool where N: VisitWith<Self>, { let mut v = IdentUsageFinder { ident, found: false, }; node.visit_with(&mut v); v.found } } impl ExprCtx { pub fn consume_depth(self) -> Option<Self> { if self.remaining_depth == 0 { return None; } Some(Self { remaining_depth: self.remaining_depth - 1, ..self }) } /// make a new expression which evaluates `val` preserving side effects, if /// any. pub fn preserve_effects<I>(self, span: Span, val: Box<Expr>, exprs: I) -> Box<Expr> where I: IntoIterator<Item = Box<Expr>>, { let mut exprs = exprs.into_iter().fold(Vec::new(), |mut v, e| { self.extract_side_effects_to(&mut v, *e); v }); if exprs.is_empty() { val } else { exprs.push(val); SeqExpr { exprs, span }.into() } } /// Add side effects of `expr` to `to`. // /// This function preserves order and conditions. (think a() ? yield b() : /// c()) #[allow(clippy::vec_box)] pub fn extract_side_effects_to(self, to: &mut Vec<Box<Expr>>, expr: Expr) { match expr { Expr::Lit(..) | Expr::This(..) | Expr::Fn(..) | Expr::Arrow(..) | Expr::PrivateName(..) => {} Expr::Ident(..) => { if expr.may_have_side_effects(self) { to.push(Box::new(expr)); } } // In most case, we can do nothing for this. Expr::Update(_) | Expr::Assign(_) | Expr::Yield(_) | Expr::Await(_) => { to.push(Box::new(expr)) } // TODO Expr::MetaProp(_) => to.push(Box::new(expr)), Expr::Call(_) => to.push(Box::new(expr)), Expr::New(e) => { // Known constructors if let Expr::Ident(Ident { ref sym, .. }) = *e.callee { if *sym == "Date" && e.args.is_empty() { return; } } to.push(e.into()) } Expr::Member(_) | Expr::SuperProp(_) => to.push(Box::new(expr)), // We are at here because we could not determine value of test. //TODO: Drop values if it does not have side effects. Expr::Cond(_) => to.push(Box::new(expr)), Expr::Unary(UnaryExpr { op: op!("typeof"), arg, .. }) => { // We should ignore side effect of `__dirname` in // // typeof __dirname != void 0 // // https://github.com/swc-project/swc/pull/7763 if arg.is_ident() { return; } self.extract_side_effects_to(to, *arg) } Expr::Unary(UnaryExpr { arg, .. }) => self.extract_side_effects_to(to, *arg), Expr::Bin(BinExpr { op, .. }) if op.may_short_circuit() => { to.push(Box::new(expr)); } Expr::Bin(BinExpr { left, right, .. }) => { self.extract_side_effects_to(to, *left); self.extract_side_effects_to(to, *right); } Expr::Seq(SeqExpr { exprs, .. }) => exprs .into_iter() .for_each(|e| self.extract_side_effects_to(to, *e)), Expr::Paren(e) => self.extract_side_effects_to(to, *e.expr), Expr::Object(ObjectLit { span, mut props, .. }) => { // let mut has_spread = false; props.retain(|node| match node { PropOrSpread::Prop(node) => match &**node { Prop::Shorthand(..) => false, Prop::KeyValue(KeyValueProp { key, value }) => { if let PropName::Computed(e) = key { if e.expr.may_have_side_effects(self) { return true; } } value.may_have_side_effects(self) } Prop::Getter(GetterProp { key, .. }) | Prop::Setter(SetterProp { key, .. }) | Prop::Method(MethodProp { key, .. }) => { if let PropName::Computed(e) = key { e.expr.may_have_side_effects(self) } else { false } } Prop::Assign(..) => { unreachable!("assign property in object literal is not a valid syntax") } }, PropOrSpread::Spread(SpreadElement { .. }) => { has_spread = true; true } }); if has_spread { to.push(ObjectLit { span, props }.into()) } else { props.into_iter().for_each(|prop| match prop { PropOrSpread::Prop(node) => match *node { Prop::Shorthand(..) => {} Prop::KeyValue(KeyValueProp { key, value }) => { if let PropName::Computed(e) = key { self.extract_side_effects_to(to, *e.expr); } self.extract_side_effects_to(to, *value) } Prop::Getter(GetterProp { key, .. }) | Prop::Setter(SetterProp { key, .. }) | Prop::Method(MethodProp { key, .. }) => { if let PropName::Computed(e) = key { self.extract_side_effects_to(to, *e.expr) } } Prop::Assign(..) => { unreachable!( "assign property in object literal is not a valid syntax" ) } }, _ => unreachable!(), }) } } Expr::Array(ArrayLit { elems, .. }) => { elems.into_iter().flatten().fold(to, |v, e| { self.extract_side_effects_to(v, *e.expr); v }); } Expr::TaggedTpl(TaggedTpl { tag, tpl, .. }) => { self.extract_side_effects_to(to, *tag); tpl.exprs .into_iter() .for_each(|e| self.extract_side_effects_to(to, *e)); } Expr::Tpl(Tpl { exprs, .. }) => { exprs .into_iter() .for_each(|e| self.extract_side_effects_to(to, *e)); } Expr::Class(ClassExpr { .. }) => unimplemented!("add_effects for class expression"), Expr::JSXMember(..) | Expr::JSXNamespacedName(..) | Expr::JSXEmpty(..) | Expr::JSXElement(..) | Expr::JSXFragment(..) => to.push(Box::new(expr)), Expr::TsTypeAssertion(TsTypeAssertion { expr, .. }) | Expr::TsNonNull(TsNonNullExpr { expr, .. }) | Expr::TsAs(TsAsExpr { expr, .. }) | Expr::TsConstAssertion(TsConstAssertion { expr, .. }) | Expr::TsInstantiation(TsInstantiation { expr, .. }) | Expr::TsSatisfies(TsSatisfiesExpr { expr, .. }) => { self.extract_side_effects_to(to, *expr) } Expr::OptChain(..) => to.push(Box::new(expr)), Expr::Invalid(..) => unreachable!(), } } } pub fn prop_name_eq(p: &PropName, key: &str) -> bool { match p { PropName::Ident(i) => i.sym == *key, PropName::Str(s) => s.value == *key, PropName::Num(n) => n.value.to_string() == *key, PropName::BigInt(_) => false, PropName::Computed(e) => match &*e.expr { Expr::Lit(Lit::Str(Str { value, .. })) => *value == *key, _ => false, }, } } /// Replace all `from` in `expr` with `to`. /// /// # Usage /// /// ```ignore /// replace_ident(&mut dec.expr, cls_name.to_id(), alias); /// ``` pub fn replace_ident<T>(node: &mut T, from: Id, to: &Ident) where T: for<'any> VisitMutWith<IdentReplacer<'any>>, { node.visit_mut_with(&mut IdentReplacer { from, to }) } pub struct IdentReplacer<'a> { from: Id, to: &'a Ident, } impl VisitMut for IdentReplacer<'_> { noop_visit_mut_type!(); visit_mut_obj_and_computed!(); fn visit_mut_prop(&mut self, node: &mut Prop) { match node { Prop::Shorthand(i) => { let cloned = i.clone(); i.visit_mut_with(self); if i.sym != cloned.sym || i.ctxt != cloned.ctxt { *node = Prop::KeyValue(KeyValueProp { key: PropName::Ident(IdentName::new(cloned.sym, cloned.span)), value: i.clone().into(), }); } } _ => { node.visit_mut_children_with(self); } } } fn visit_mut_ident(&mut self, node: &mut Ident) { if node.sym == self.from.0 && node.ctxt == self.from.1 { *node = self.to.clone(); } } } pub struct BindingCollector<I> where I: IdentLike + Eq + Hash + Send + Sync, { only: Option<SyntaxContext>, bindings: FxHashSet<I>, is_pat_decl: bool, } impl<I> BindingCollector<I> where I: IdentLike + Eq + Hash + Send + Sync, { fn add(&mut self, i: &Ident) { if let Some(only) = self.only { if only != i.ctxt { return; } } self.bindings.insert(I::from_ident(i)); } } impl<I> Visit for BindingCollector<I> where I: IdentLike + Eq + Hash + Send + Sync, { noop_visit_type!(); fn visit_arrow_expr(&mut self, n: &ArrowExpr) { let old = self.is_pat_decl; for p in &n.params { self.is_pat_decl = true; p.visit_with(self); } n.body.visit_with(self); self.is_pat_decl = old; } fn visit_assign_pat_prop(&mut self, node: &AssignPatProp) { node.value.visit_with(self); if self.is_pat_decl { self.add(&node.key.clone().into()); } } fn visit_class_decl(&mut self, node: &ClassDecl) { node.visit_children_with(self); self.add(&node.ident); } fn visit_expr(&mut self, node: &Expr) { let old = self.is_pat_decl; self.is_pat_decl = false; node.visit_children_with(self); self.is_pat_decl = old; } fn visit_export_default_decl(&mut self, e: &ExportDefaultDecl) { match &e.decl { DefaultDecl::Class(ClassExpr { ident: Some(ident), .. }) => { self.add(ident); } DefaultDecl::Fn(FnExpr { ident: Some(ident), function: f, }) if f.body.is_some() => { self.add(ident); } _ => {} } e.visit_children_with(self); } fn visit_fn_decl(&mut self, node: &FnDecl) { node.visit_children_with(self); self.add(&node.ident); } fn visit_import_default_specifier(&mut self, node: &ImportDefaultSpecifier) { self.add(&node.local); } fn visit_import_named_specifier(&mut self, node: &ImportNamedSpecifier) { self.add(&node.local); } fn visit_import_star_as_specifier(&mut self, node: &ImportStarAsSpecifier) { self.add(&node.local); } fn visit_param(&mut self, node: &Param) { let old = self.is_pat_decl; self.is_pat_decl = true; node.visit_children_with(self); self.is_pat_decl = old; } fn visit_pat(&mut self, node: &Pat) { node.visit_children_with(self); if self.is_pat_decl { if let Pat::Ident(i) = node { self.add(&i.clone().into()) } } } fn visit_var_declarator(&mut self, node: &VarDeclarator) { let old = self.is_pat_decl; self.is_pat_decl = true; node.name.visit_with(self); self.is_pat_decl = false; node.init.visit_with(self); self.is_pat_decl = old; } } /// Collects binding identifiers. pub fn collect_decls<I, N>(n: &N) -> FxHashSet<I> where I: IdentLike + Eq + Hash + Send + Sync, N: VisitWith<BindingCollector<I>>, { let mut v = BindingCollector { only: None, bindings: Default::default(), is_pat_decl: false, }; n.visit_with(&mut v); v.bindings } /// Collects binding identifiers, but only if it has a context which is /// identical to `ctxt`. pub fn collect_decls_with_ctxt<I, N>(n: &N, ctxt: SyntaxContext) -> FxHashSet<I> where I: IdentLike + Eq + Hash + Send + Sync, N: VisitWith<BindingCollector<I>>, { let mut v = BindingCollector { only: Some(ctxt), bindings: Default::default(), is_pat_decl: false, }; n.visit_with(&mut v); v.bindings } pub struct TopLevelAwait { found: bool, } impl Visit for TopLevelAwait { noop_visit_type!(); fn visit_stmt(&mut self, n: &Stmt) { if !self.found { n.visit_children_with(self); } } fn visit_param(&mut self, _: &Param) {} fn visit_function(&mut self, _: &Function) {} fn visit_arrow_expr(&mut self, _: &ArrowExpr) {} fn visit_class_member(&mut self, prop: &ClassMember) { match prop { ClassMember::ClassProp(ClassProp { key: PropName::Computed(computed), .. }) | ClassMember::Method(ClassMethod { key: PropName::Computed(computed), .. }) => computed.visit_children_with(self), _ => (), }; } fn visit_prop(&mut self, prop: &Prop) { match prop { Prop::KeyValue(KeyValueProp { key: PropName::Computed(computed), .. }) | Prop::Getter(GetterProp { key: PropName::Computed(computed), .. }) | Prop::Setter(SetterProp { key: PropName::Computed(computed), .. }) | Prop::Method(MethodProp { key: PropName::Computed(computed), .. }) => computed.visit_children_with(self), _ => {} } } fn visit_for_of_stmt(&mut self, for_of_stmt: &ForOfStmt) { if for_of_stmt.is_await { self.found = true; return; } for_of_stmt.visit_children_with(self); } fn visit_await_expr(&mut self, _: &AwaitExpr) { self.found = true; } } pub fn contains_top_level_await<V: VisitWith<TopLevelAwait>>(t: &V) -> bool { let mut finder = TopLevelAwait { found: false }; t.visit_with(&mut finder); finder.found } /// Variable remapper /// /// This visitor modifies [SyntaxContext] while preserving the symbol of /// [Ident]s. pub struct Remapper<'a> { vars: &'a FxHashMap<Id, SyntaxContext>, } impl<'a> Remapper<'a> { pub fn new(vars: &'a FxHashMap<Id, SyntaxContext>) -> Self { Self { vars } } } impl VisitMut for Remapper<'_> { noop_visit_mut_type!(fail); fn visit_mut_ident(&mut self, i: &mut Ident) { if let Some(new_ctxt) = self.vars.get(&i.to_id()).copied() { i.ctxt = new_ctxt; } } } /// Replacer for [Id] => ]Id] pub struct IdentRenamer<'a> { map: &'a FxHashMap<Id, Id>, } impl<'a> IdentRenamer<'a> { pub fn new(map: &'a FxHashMap<Id, Id>) -> Self { Self { map } } } impl VisitMut for IdentRenamer<'_> { noop_visit_mut_type!(); visit_mut_obj_and_computed!(); fn visit_mut_export_named_specifier(&mut self, node: &mut ExportNamedSpecifier) { if node.exported.is_some() { node.orig.visit_mut_children_with(self); return; } match &mut node.orig { ModuleExportName::Ident(orig) => { if let Some(new) = self.map.get(&orig.to_id()) { node.exported = Some(ModuleExportName::Ident(orig.clone())); orig.sym = new.0.clone(); orig.ctxt = new.1; } } ModuleExportName::Str(_) => {} } } fn visit_mut_ident(&mut self, node: &mut Ident) { if let Some(new) = self.map.get(&node.to_id()) { node.sym = new.0.clone(); node.ctxt = new.1; } } fn visit_mut_object_pat_prop(&mut self, i: &mut ObjectPatProp) { match i { ObjectPatProp::Assign(p) => { p.value.visit_mut_with(self); let orig = p.key.clone(); p.key.visit_mut_with(self); if orig.to_id() == p.key.to_id() { return; } match p.value.take() { Some(default) => { *i = ObjectPatProp::KeyValue(KeyValuePatProp { key: PropName::Ident(orig.clone().into()), value: AssignPat { span: DUMMY_SP, left: p.key.clone().into(), right: default, } .into(), }); } None => { *i = ObjectPatProp::KeyValue(KeyValuePatProp { key: PropName::Ident(orig.clone().into()), value: p.key.clone().into(), }); } } } _ => { i.visit_mut_children_with(self); } } } fn visit_mut_prop(&mut self, node: &mut Prop) { match node { Prop::Shorthand(i) => { let cloned = i.clone(); i.visit_mut_with(self); if i.sym != cloned.sym || i.ctxt != cloned.ctxt { *node = Prop::KeyValue(KeyValueProp { key: PropName::Ident(IdentName::new(cloned.sym, cloned.span)), value: i.clone().into(), }); } } _ => { node.visit_mut_children_with(self); } } } } pub trait QueryRef { fn query_ref(&self, _ident: &Ident) -> Option<Box<Expr>> { None } fn query_lhs(&self, _ident: &Ident) -> Option<Box<Expr>> { None } /// ref used in JSX fn query_jsx(&self, _ident: &Ident) -> Option<JSXElementName> { None } /// when `foo()` is replaced with `bar.baz()`, /// should `bar.baz` be indirect call? fn should_fix_this(&self, _ident: &Ident) -> bool { false } } /// Replace `foo` with `bar` or `bar.baz` pub struct RefRewriter<T> where T: QueryRef, { pub query: T, } impl<T> RefRewriter<T> where T: QueryRef, { pub fn exit_prop(&mut self, n: &mut Prop) { if let Prop::Shorthand(shorthand) = n { if let Some(expr) = self.query.query_ref(shorthand) { *n = KeyValueProp { key: shorthand.take().into(), value: expr, } .into() } } } pub fn exit_pat(&mut self, n: &mut Pat) { if let Pat::Ident(id) = n { if let Some(expr) = self.query.query_lhs(&id.clone().into()) { *n = expr.into(); } } } pub fn exit_expr(&mut self, n: &mut Expr) { if let Expr::Ident(ref_ident) = n { if let Some(expr) = self.query.query_ref(ref_ident) { *n = *expr; } }; } pub fn exit_simple_assign_target(&mut self, n: &mut SimpleAssignTarget) { if let SimpleAssignTarget::Ident(ref_ident) = n { if let Some(expr) = self.query.query_lhs(&ref_ident.clone().into()) { *n = expr.try_into().unwrap(); } }; } pub fn exit_jsx_element_name(&mut self, n: &mut JSXElementName) { if let JSXElementName::Ident(ident) = n { if let Some(expr) = self.query.query_jsx(ident) { *n = expr; } } } pub fn exit_jsx_object(&mut self, n: &mut JSXObject) { if let JSXObject::Ident(ident) = n { if let Some(expr) = self.query.query_jsx(ident) { *n = match expr { JSXElementName::Ident(ident) => ident.into(), JSXElementName::JSXMemberExpr(expr) => Box::new(expr).into(), JSXElementName::JSXNamespacedName(..) => unimplemented!(), } } } } pub fn exit_object_pat_prop(&mut self, n: &mut ObjectPatProp) { if let ObjectPatProp::Assign(AssignPatProp { key, value, .. }) = n { if let Some(expr) = self.query.query_lhs(&key.id) { let value = value .take() .map(|default_value| { let left = expr.clone().try_into().unwrap(); Box::new(default_value.make_assign_to(op!("="), left)) }) .unwrap_or(expr); *n = ObjectPatProp::KeyValue(KeyValuePatProp { key: PropName::Ident(key.take().into()), value: value.into(), }); } } } } impl<T> VisitMut for RefRewriter<T> where T: QueryRef, { /// replace bar in binding pattern /// input: /// ```JavaScript /// const foo = { bar } /// ``` /// output: /// ```JavaScript /// cobst foo = { bar: baz } /// ``` fn visit_mut_prop(&mut self, n: &mut Prop) { n.visit_mut_children_with(self); self.exit_prop(n); } fn visit_mut_var_declarator(&mut self, n: &mut VarDeclarator) { if !n.name.is_ident() { n.name.visit_mut_with(self); } // skip var declarator name n.init.visit_mut_with(self); } fn visit_mut_pat(&mut self, n: &mut Pat) { n.visit_mut_children_with(self); self.exit_pat(n); } fn visit_mut_expr(&mut self, n: &mut Expr) { n.visit_mut_children_with(self); self.exit_expr(n); } fn visit_mut_simple_assign_target(&mut self, n: &mut SimpleAssignTarget) { n.visit_mut_children_with(self); self.exit_simple_assign_target(n); } fn visit_mut_callee(&mut self, n: &mut Callee) { match n { Callee::Expr(e) if e.as_ident() .map(|ident| self.query.should_fix_this(ident)) .unwrap_or_default() => { e.visit_mut_with(self); if e.is_member() { *n = n.take().into_indirect() } } _ => n.visit_mut_children_with(self), } } fn visit_mut_tagged_tpl(&mut self, n: &mut TaggedTpl) { let should_fix_this = n .tag .as_ident() .map(|ident| self.query.should_fix_this(ident)) .unwrap_or_default(); n.visit_mut_children_with(self); if should_fix_this && n.tag.is_member() { *n = n.take().into_indirect() } } fn visit_mut_jsx_element_name(&mut self, n: &mut JSXElementName) { n.visit_mut_children_with(self); self.exit_jsx_element_name(n); } fn visit_mut_jsx_object(&mut self, n: &mut JSXObject) { n.visit_mut_children_with(self); self.exit_jsx_object(n); } } fn is_immutable_value(expr: &Expr) -> bool { // TODO(johnlenz): rename this function. It is currently being used // in two disjoint cases: // 1) We only care about the result of the expression (in which case NOT here // should return true) // 2) We care that expression is a side-effect free and can't be side-effected // by other expressions. // This should only be used to say the value is immutable and // hasSideEffects and canBeSideEffected should be used for the other case. match *expr { Expr::Lit(Lit::Bool(..)) | Expr::Lit(Lit::Str(..)) | Expr::Lit(Lit::Num(..)) | Expr::Lit(Lit::Null(..)) => true, Expr::Unary(UnaryExpr { op: op!("!"), ref arg, .. }) | Expr::Unary(UnaryExpr { op: op!("~"), ref arg, .. }) | Expr::Unary(UnaryExpr { op: op!("void"), ref arg, .. }) => arg.is_immutable_value(), Expr::Ident(ref i) => i.sym == "undefined" || i.sym == "Infinity" || i.sym == "NaN", Expr::Tpl(Tpl { ref exprs, .. }) => exprs.iter().all(|e| e.is_immutable_value()), _ => false, } } fn is_number(expr: &Expr) -> bool { matches!(*expr, Expr::Lit(Lit::Num(..))) } fn is_str(expr: &Expr) -> bool { match expr { Expr::Lit(Lit::Str(..)) | Expr::Tpl(_) => true, Expr::Unary(UnaryExpr { op: op!("typeof"), .. }) => true, Expr::Bin(BinExpr { op: op!(bin, "+"), left, right, .. }) => left.is_str() || right.is_str(), Expr::Assign(AssignExpr { op: op!("=") | op!("+="), right, .. }) => right.is_str(), Expr::Seq(s) => s.exprs.last().unwrap().is_str(), Expr::Cond(CondExpr { cons, alt, .. }) => cons.is_str() && alt.is_str(), _ => false, } } fn is_array_lit(expr: &Expr) -> bool { matches!(*expr, Expr::Array(..)) } fn is_nan(expr: &Expr) -> bool { // NaN is special expr.is_ident_ref_to("NaN") } fn is_undefined(expr: &Expr, ctx: ExprCtx) -> bool { expr.is_global_ref_to(ctx, "undefined") } fn is_void(expr: &Expr) -> bool { matches!( *expr, Expr::Unary(UnaryExpr { op: op!("void"), .. }) ) } fn is_global_ref_to(expr: &Expr, ctx: ExprCtx, id: &str) -> bool { match expr { Expr::Ident(i) => i.ctxt == ctx.unresolved_ctxt && &*i.sym == id, _ => false, } } fn is_one_of_global_ref_to(expr: &Expr, ctx: ExprCtx, ids: &[&str]) -> bool { match expr { Expr::Ident(i) => i.ctxt == ctx.unresolved_ctxt && ids.contains(&&*i.sym), _ => false, } } fn as_pure_bool(expr: &Expr, ctx: ExprCtx) -> BoolValue { match expr.cast_to_bool(ctx) { (Pure, Known(b)) => Known(b), _ => Unknown, } } fn cast_to_bool(expr: &Expr, ctx: ExprCtx) -> (Purity, BoolValue) { let Some(ctx) = ctx.consume_depth() else { return (MayBeImpure, Unknown); }; if expr.is_global_ref_to(ctx, "undefined") { return (Pure, Known(false)); } if expr.is_nan() { return (Pure, Known(false)); } let val = match expr { Expr::Paren(ref e) => return e.expr.cast_to_bool(ctx), Expr::Assign(AssignExpr { ref right, op: op!("="), .. }) => { let (_, v) = right.cast_to_bool(ctx); return (MayBeImpure, v); } Expr::Unary(UnaryExpr { op: op!(unary, "-"), arg, .. }) => { let v = arg.as_pure_number(ctx); match v { Known(n) => Known(!matches!(n.classify(), FpCategory::Nan | FpCategory::Zero)), Unknown => return (MayBeImpure, Unknown), } } Expr::Unary(UnaryExpr { op: op!("!"), ref arg, .. }) => { let (p, v) = arg.cast_to_bool(ctx); return (p, !v); } Expr::Seq(SeqExpr { exprs, .. }) => exprs.last().unwrap().cast_to_bool(ctx).1, Expr::Bin(BinExpr { left, op: op!(bin, "-"), right, .. }) => { let (lp, ln) = left.cast_to_number(ctx); let (rp, rn) = right.cast_to_number(ctx); return ( lp + rp, match (ln, rn) { (Known(ln), Known(rn)) => { if ln == rn { Known(false) } else { Known(true) } } _ => Unknown, }, ); } Expr::Bin(BinExpr { left, op: op!("/"), right, .. }) => { let lv = left.as_pure_number(ctx); let rv = right.as_pure_number(ctx); match (lv, rv) { (Known(lv), Known(rv)) => { // NaN is false if lv == 0.0 && rv == 0.0 { return (Pure, Known(false)); } // Infinity is true. if rv == 0.0 { return (Pure, Known(true)); } let v = lv / rv; return (Pure, Known(v != 0.0)); } _ => Unknown, } } Expr::Bin(BinExpr { ref left, op: op @ op!("&"), ref right, .. }) | Expr::Bin(BinExpr { ref left, op: op @ op!("|"), ref right, .. }) => { if left.get_type(ctx) != Known(BoolType) || right.get_type(ctx) != Known(BoolType) { return (MayBeImpure, Unknown); } // TODO: Ignore purity if value cannot be reached. let (lp, lv) = left.cast_to_bool(ctx); let (rp, rv) = right.cast_to_bool(ctx); let v = if *op == op!("&") { lv.and(rv) } else { lv.or(rv) }; if lp + rp == Pure { return (Pure, v); } v } Expr::Bin(BinExpr { ref left, op: op!("||"), ref right, .. }) => { let (lp, lv) = left.cast_to_bool(ctx); if let Known(true) = lv { return (lp, lv); } let (rp, rv) = right.cast_to_bool(ctx); if let Known(true) = rv { return (lp + rp, rv); } Unknown } Expr::Bin(BinExpr { ref left, op: op!("&&"), ref right, .. }) => { let (lp, lv) = left.cast_to_bool(ctx); if let Known(false) = lv { return (lp, lv); } let (rp, rv) = right.cast_to_bool(ctx); if let Known(false) = rv { return (lp + rp, rv); } Unknown } Expr::Bin(BinExpr { left, op: op!(bin, "+"), right, .. }) => { match &**left { Expr::Lit(Lit::Str(s)) if !s.value.is_empty() => return (MayBeImpure, Known(true)), _ => {} } match &**right { Expr::Lit(Lit::Str(s)) if !s.value.is_empty() => return (MayBeImpure, Known(true)), _ => {} } Unknown } Expr::Fn(..) | Expr::Class(..) | Expr::New(..) | Expr::Array(..) | Expr::Object(..) => { Known(true) } Expr::Unary(UnaryExpr { op: op!("void"), .. }) => Known(false), Expr::Lit(ref lit) => { return ( Pure, Known(match *lit { Lit::Num(Number { value: n, .. }) => { !matches!(n.classify(), FpCategory::Nan | FpCategory::Zero) } Lit::BigInt(ref v) => v .value .to_string() .contains(|c: char| matches!(c, '1'..='9')), Lit::Bool(b) => b.value, Lit::Str(Str { ref value, .. }) => !value.is_empty(), Lit::Null(..) => false, Lit::Regex(..) => true, Lit::JSXText(..) => unreachable!("as_bool() for JSXText"), }), ); } //TODO? _ => Unknown, }; if expr.may_have_side_effects(ctx) { (MayBeImpure, val) } else { (Pure, val) } } fn cast_to_number(expr: &Expr, ctx: ExprCtx) -> (Purity, Value<f64>) { let Some(ctx) = ctx.consume_depth() else { return (MayBeImpure, Unknown); }; let v = match expr { Expr::Lit(l) => match l { Lit::Bool(Bool { value: true, .. }) => 1.0, Lit::Bool(Bool { value: false, .. }) | Lit::Null(..) => 0.0, Lit::Num(Number { value: n, .. }) => *n, Lit::Str(Str { value, .. }) => return (Pure, num_from_str(value)), _ => return (Pure, Unknown), }, Expr::Array(..) => { let Known(s) = expr.as_pure_string(ctx) else { return (Pure, Unknown); }; return (Pure, num_from_str(&s)); } Expr::Ident(Ident { sym, ctxt, .. }) => match &**sym { "undefined" | "NaN" if *ctxt == ctx.unresolved_ctxt => f64::NAN, "Infinity" if *ctxt == ctx.unresolved_ctxt => f64::INFINITY, _ => return (Pure, Unknown), }, Expr::Unary(UnaryExpr { op: op!(unary, "-"), arg, .. }) => match arg.cast_to_number(ctx) { (Pure, Known(v)) => -v, _ => return (MayBeImpure, Unknown), }, Expr::Unary(UnaryExpr { op: op!("!"), ref arg, .. }) => match arg.cast_to_bool(ctx) { (Pure, Known(v)) => { if v { 0.0 } else { 1.0 } } _ => return (MayBeImpure, Unknown), }, Expr::Unary(UnaryExpr { op: op!("void"), ref arg, .. }) => { if arg.may_have_side_effects(ctx) { return (MayBeImpure, Known(f64::NAN)); } else { f64::NAN } } Expr::Tpl(..) => { return ( Pure, num_from_str(&match expr.as_pure_string(ctx) { Known(v) => v, Unknown => return (MayBeImpure, Unknown), }), ); } Expr::Seq(seq) => { if let Some(last) = seq.exprs.last() { let (_, v) = last.cast_to_number(ctx); // TODO: Purity return (MayBeImpure, v); } return (MayBeImpure, Unknown); } _ => return (MayBeImpure, Unknown), }; (Purity::Pure, Known(v)) } fn as_pure_number(expr: &Expr, ctx: ExprCtx) -> Value<f64> { let (purity, v) = expr.cast_to_number(ctx); if !purity.is_pure() { return Unknown; } v } fn as_pure_string(expr: &Expr, ctx: ExprCtx) -> Value<Cow<'_, str>> { let Some(ctx) = ctx.consume_depth() else { return Unknown; }; match *expr { Expr::Lit(ref l) => match *l { Lit::Str(Str { ref value, .. }) => Known(Cow::Borrowed(value)), Lit::Num(ref n) => { if n.value == -0.0 { return Known(Cow::Borrowed("0")); } Known(Cow::Owned(n.value.to_js_string())) } Lit::Bool(Bool { value: true, .. }) => Known(Cow::Borrowed("true")), Lit::Bool(Bool { value: false, .. }) => Known(Cow::Borrowed("false")), Lit::Null(..) => Known(Cow::Borrowed("null")), _ => Unknown, }, Expr::Tpl(_) => { Value::Unknown // TODO: // Only convert a template literal if all its expressions // can be converted. // unimplemented!("TplLit. as_string()") } Expr::Ident(Ident { ref sym, ctxt, .. }) => match &**sym { "undefined" | "Infinity" | "NaN" if ctxt == ctx.unresolved_ctxt => { Known(Cow::Borrowed(&**sym)) } _ => Unknown, }, Expr::Unary(UnaryExpr { op: op!("void"), .. }) => Known(Cow::Borrowed("undefined")), Expr::Unary(UnaryExpr { op: op!("!"), ref arg, .. }) => Known(Cow::Borrowed(match arg.as_pure_bool(ctx) { Known(v) => { if v { "false" } else { "true" } } Unknown => return Value::Unknown, })), Expr::Array(ArrayLit { ref elems, .. }) => { let mut buf = String::new(); let len = elems.len(); // null, undefined is "" in array literal. for (idx, elem) in elems.iter().enumerate() { let last = idx == len - 1; let e = match *elem { Some(ref elem) => { let ExprOrSpread { ref expr, .. } = *elem; match &**expr { Expr::Lit(Lit::Null(..)) => Cow::Borrowed(""), Expr::Unary(UnaryExpr { op: op!("void"), arg, .. }) => { if arg.may_have_side_effects(ctx) { return Value::Unknown; } Cow::Borrowed("") } Expr::Ident(Ident { sym: undefined, .. }) if &**undefined == "undefined" => { Cow::Borrowed("") } _ => match expr.as_pure_string(ctx) { Known(v) => v, Unknown => return Value::Unknown, }, } } None => Cow::Borrowed(""), }; buf.push_str(&e); if !last { buf.push(','); } } Known(buf.into()) } _ => Unknown, } } fn get_type(expr: &Expr, ctx: ExprCtx) -> Value<Type> { let Some(ctx) = ctx.consume_depth() else { return Unknown; }; match expr { Expr::Assign(AssignExpr { ref right, op: op!("="), .. }) => right.get_type(ctx), Expr::Member(MemberExpr { obj, prop: MemberProp::Ident(IdentName { sym: length, .. }), .. }) if &**length == "length" => match &**obj { Expr::Array(ArrayLit { .. }) | Expr::Lit(Lit::Str(..)) => Known(Type::Num), Expr::Ident(Ident { sym: arguments, .. }) if &**arguments == "arguments" => { Known(Type::Num) } _ => Unknown, }, Expr::Seq(SeqExpr { ref exprs, .. }) => exprs .last() .expect("sequence expression should not be empty") .get_type(ctx), Expr::Bin(BinExpr { ref left, op: op!("&&"), ref right, .. }) | Expr::Bin(BinExpr { ref left, op: op!("||"), ref right, .. }) | Expr::Cond(CondExpr { cons: ref left, alt: ref right, .. }) => and(left.get_type(ctx), right.get_type(ctx)), Expr::Bin(BinExpr { ref left, op: op!(bin, "+"), ref right, .. }) => { let rt = right.get_type(ctx); if rt == Known(StringType) { return Known(StringType); } let lt = left.get_type(ctx); if lt == Known(StringType) { return Known(StringType); } // There are some pretty weird cases for object types: // {} + [] === "0" // [] + {} ==== "[object Object]" if lt == Known(ObjectType) || rt == Known(ObjectType) { return Unknown; } if !may_be_str(lt) && !may_be_str(rt) { // ADD used with compilations of null, boolean and number always // result in numbers. return Known(NumberType); } // There are some pretty weird cases for object types: // {} + [] === "0" // [] + {} ==== "[object Object]" Unknown } Expr::Assign(AssignExpr { op: op!("+="), ref right, .. }) => { if right.get_type(ctx) == Known(StringType) { return Known(StringType); } Unknown } Expr::Ident(Ident { ref sym, .. }) => Known(match &**sym { "undefined" => UndefinedType, "NaN" | "Infinity" => NumberType, _ => return Unknown, }), Expr::Lit(Lit::Num(..)) | Expr::Assign(AssignExpr { op: op!("&="), .. }) | Expr::Assign(AssignExpr { op: op!("^="), .. }) | Expr::Assign(AssignExpr { op: op!("|="), .. }) | Expr::Assign(AssignExpr { op: op!("<<="), .. }) | Expr::Assign(AssignExpr { op: op!(">>="), .. }) | Expr::Assign(AssignExpr { op: op!(">>>="), .. }) | Expr::Assign(AssignExpr { op: op!("-="), .. }) | Expr::Assign(AssignExpr { op: op!("*="), .. }) | Expr::Assign(AssignExpr { op: op!("**="), .. }) | Expr::Assign(AssignExpr { op: op!("/="), .. }) | Expr::Assign(AssignExpr { op: op!("%="), .. }) | Expr::Unary(UnaryExpr { op: op!("~"), .. }) | Expr::Bin(BinExpr { op: op!("|"), .. }) | Expr::Bin(BinExpr { op: op!("^"), .. }) | Expr::Bin(BinExpr { op: op!("&"), .. }) | Expr::Bin(BinExpr { op: op!("<<"), .. }) | Expr::Bin(BinExpr { op: op!(">>"), .. }) | Expr::Bin(BinExpr { op: op!(">>>"), .. }) | Expr::Bin(BinExpr { op: op!(bin, "-"), .. }) | Expr::Bin(BinExpr { op: op!("*"), .. }) | Expr::Bin(BinExpr { op: op!("%"), .. }) | Expr::Bin(BinExpr { op: op!("/"), .. }) | Expr::Bin(BinExpr { op: op!("**"), .. }) | Expr::Update(UpdateExpr { op: op!("++"), .. }) | Expr::Update(UpdateExpr { op: op!("--"), .. }) | Expr::Unary(UnaryExpr { op: op!(unary, "+"), .. }) | Expr::Unary(UnaryExpr { op: op!(unary, "-"), .. }) => Known(NumberType), // Primitives Expr::Lit(Lit::Bool(..)) | Expr::Bin(BinExpr { op: op!("=="), .. }) | Expr::Bin(BinExpr { op: op!("!="), .. }) | Expr::Bin(BinExpr { op: op!("==="), .. }) | Expr::Bin(BinExpr { op: op!("!=="), .. }) | Expr::Bin(BinExpr { op: op!("<"), .. }) | Expr::Bin(BinExpr { op: op!("<="), .. }) | Expr::Bin(BinExpr { op: op!(">"), .. }) | Expr::Bin(BinExpr { op: op!(">="), .. }) | Expr::Bin(BinExpr { op: op!("in"), .. }) | Expr::Bin(BinExpr { op: op!("instanceof"), .. }) | Expr::Unary(UnaryExpr { op: op!("!"), .. }) | Expr::Unary(UnaryExpr { op: op!("delete"), .. }) => Known(BoolType), Expr::Unary(UnaryExpr { op: op!("typeof"), .. }) | Expr::Lit(Lit::Str { .. }) | Expr::Tpl(..) => Known(StringType), Expr::Lit(Lit::Null(..)) => Known(NullType), Expr::Unary(UnaryExpr { op: op!("void"), .. }) => Known(UndefinedType), Expr::Fn(..) | Expr::New(NewExpr { .. }) | Expr::Array(ArrayLit { .. }) | Expr::Object(ObjectLit { .. }) | Expr::Lit(Lit::Regex(..)) => Known(ObjectType), _ => Unknown, } } fn is_pure_callee(expr: &Expr, ctx: ExprCtx) -> bool { if expr.is_global_ref_to(ctx, "Date") { return true; } match expr { Expr::Member(MemberExpr { obj, prop: MemberProp::Ident(prop), .. }) => { obj.is_global_ref_to(ctx, "Math") || match &**obj { // Allow dummy span Expr::Ident(Ident { ctxt, sym: math, .. }) => &**math == "Math" && *ctxt == SyntaxContext::empty(), // Some methods of string are pure Expr::Lit(Lit::Str(..)) => match &*prop.sym { "charAt" | "charCodeAt" | "concat" | "endsWith" | "includes" | "indexOf" | "lastIndexOf" | "localeCompare" | "slice" | "split" | "startsWith" | "substr" | "substring" | "toLocaleLowerCase" | "toLocaleUpperCase" | "toLowerCase" | "toString" | "toUpperCase" | "trim" | "trimEnd" | "trimStart" => true, _ => false, }, _ => false, } } Expr::Fn(FnExpr { function: f, .. }) if f.params.iter().all(|p| p.pat.is_ident()) && f.body.is_some() && f.body.as_ref().unwrap().stmts.is_empty() => { true } _ => false, } } fn may_have_side_effects(expr: &Expr, ctx: ExprCtx) -> bool { let Some(ctx) = ctx.consume_depth() else { return true; }; if expr.is_pure_callee(ctx) { return false; } match expr { Expr::Ident(i) => { if ctx.is_unresolved_ref_safe { return false; } if i.ctxt == ctx.unresolved_ctxt { !matches!( &*i.sym, "Infinity" | "NaN" | "Math" | "undefined" | "Object" | "Array" | "Promise" | "Boolean" | "Number" | "String" | "BigInt" | "Error" | "RegExp" | "Function" | "document" ) } else { false } } Expr::Lit(..) | Expr::This(..) | Expr::PrivateName(..) | Expr::TsConstAssertion(..) => { false } Expr::Paren(e) => e.expr.may_have_side_effects(ctx), // Function expression does not have any side effect if it's not used. Expr::Fn(..) | Expr::Arrow(..) => false, // It's annoying to pass in_strict Expr::Class(c) => class_has_side_effect(ctx, &c.class), Expr::Array(ArrayLit { elems, .. }) => elems .iter() .filter_map(|e| e.as_ref()) .any(|e| e.spread.is_some() || e.expr.may_have_side_effects(ctx)), Expr::Unary(UnaryExpr { op: op!("delete"), .. }) => true, Expr::Unary(UnaryExpr { arg, .. }) => arg.may_have_side_effects(ctx), Expr::Bin(BinExpr { left, right, .. }) => { left.may_have_side_effects(ctx) || right.may_have_side_effects(ctx) } Expr::Member(MemberExpr { obj, prop, .. }) if obj.is_object() || obj.is_fn_expr() || obj.is_arrow() || obj.is_class() => { if obj.may_have_side_effects(ctx) { return true; } match &**obj { Expr::Class(c) => { let is_static_accessor = |member: &ClassMember| { if let ClassMember::Method(ClassMethod { kind: MethodKind::Getter | MethodKind::Setter, is_static: true, .. }) = member { true } else { false } }; if c.class.body.iter().any(is_static_accessor) { return true; } } Expr::Object(obj) => { let can_have_side_effect = |prop: &PropOrSpread| match prop { PropOrSpread::Spread(_) => true, PropOrSpread::Prop(prop) => match prop.as_ref() { Prop::Getter(_) | Prop::Setter(_) | Prop::Method(_) => true, Prop::Shorthand(Ident { sym, .. }) | Prop::KeyValue(KeyValueProp { key: PropName::Ident(IdentName { sym, .. }) | PropName::Str(Str { value: sym, .. }), .. }) => &**sym == "__proto__", Prop::KeyValue(KeyValueProp { key: PropName::Computed(_), .. }) => true, _ => false, }, }; if obj.props.iter().any(can_have_side_effect) { return true; } } _ => {} }; match prop { MemberProp::Computed(c) => c.expr.may_have_side_effects(ctx), MemberProp::Ident(_) | MemberProp::PrivateName(_) => false, } } //TODO Expr::Tpl(_) => true, Expr::TaggedTpl(_) => true, Expr::MetaProp(_) => true, Expr::Await(_) | Expr::Yield(_) | Expr::Member(_) | Expr::SuperProp(_) | Expr::Update(_) | Expr::Assign(_) => true, Expr::OptChain(OptChainExpr { base, .. }) if matches!(&**base, OptChainBase::Member(_)) => { true } // TODO Expr::New(_) => true, Expr::Call(CallExpr { callee: Callee::Expr(callee), ref args, .. }) if callee.is_pure_callee(ctx) => { args.iter().any(|arg| arg.expr.may_have_side_effects(ctx)) } Expr::OptChain(OptChainExpr { base, .. }) if matches!(&**base, OptChainBase::Call(..)) && OptChainBase::as_call(base) .unwrap() .callee .is_pure_callee(ctx) => { OptChainBase::as_call(base) .unwrap() .args .iter() .any(|arg| arg.expr.may_have_side_effects(ctx)) } Expr::Call(_) | Expr::OptChain(..) => true, Expr::Seq(SeqExpr { exprs, .. }) => exprs.iter().any(|e| e.may_have_side_effects(ctx)), Expr::Cond(CondExpr { test, cons, alt, .. }) => { test.may_have_side_effects(ctx) || cons.may_have_side_effects(ctx) || alt.may_have_side_effects(ctx) } Expr::Object(ObjectLit { props, .. }) => props.iter().any(|node| match node { PropOrSpread::Prop(node) => match &**node { Prop::Shorthand(..) => false, Prop::KeyValue(KeyValueProp { key, value }) => { let k = match key { PropName::Computed(e) => e.expr.may_have_side_effects(ctx), _ => false, }; k || value.may_have_side_effects(ctx) } Prop::Getter(GetterProp { key, .. }) | Prop::Setter(SetterProp { key, .. }) | Prop::Method(MethodProp { key, .. }) => match key { PropName::Computed(e) => e.expr.may_have_side_effects(ctx), _ => false, }, Prop::Assign(_) => true, }, // may trigger getter PropOrSpread::Spread(_) => true, }), Expr::JSXMember(..) | Expr::JSXNamespacedName(..) | Expr::JSXEmpty(..) | Expr::JSXElement(..) | Expr::JSXFragment(..) => true, Expr::TsAs(TsAsExpr { ref expr, .. }) | Expr::TsNonNull(TsNonNullExpr { ref expr, .. }) | Expr::TsTypeAssertion(TsTypeAssertion { ref expr, .. }) | Expr::TsInstantiation(TsInstantiation { ref expr, .. }) | Expr::TsSatisfies(TsSatisfiesExpr { ref expr, .. }) => expr.may_have_side_effects(ctx), Expr::Invalid(..) => true, } } #[cfg(test)] mod tests { use swc_common::{input::StringInput, BytePos}; use swc_ecma_parser::{Parser, Syntax}; use super::*; #[test] fn test_collect_decls() { run_collect_decls( "const { a, b = 1, inner: { c }, ...d } = {};", &["a", "b", "c", "d"], ); run_collect_decls("const [ a, b = 1, [c], ...d ] = [];", &["a", "b", "c", "d"]); } #[test] fn test_collect_export_default_expr() { run_collect_decls("export default function foo(){}", &["foo"]); run_collect_decls("export default class Foo{}", &["Foo"]); } fn run_collect_decls(text: &str, expected_names: &[&str]) { let module = parse_module(text); let decls: FxHashSet<Id> = collect_decls(&module); let mut names = decls.iter().map(|d| d.0.to_string()).collect::<Vec<_>>(); names.sort(); assert_eq!(names, expected_names); } #[test] fn test_extract_var_ids() { run_extract_var_ids( "var { a, b = 1, inner: { c }, ...d } = {};", &["a", "b", "c", "d"], ); run_extract_var_ids("var [ a, b = 1, [c], ...d ] = [];", &["a", "b", "c", "d"]); } fn run_extract_var_ids(text: &str, expected_names: &[&str]) { let module = parse_module(text); let decls = extract_var_ids(&module); let mut names = decls.iter().map(|d| d.sym.to_string()).collect::<Vec<_>>(); names.sort(); assert_eq!(names, expected_names); } fn parse_module(text: &str) -> Module { let syntax = Syntax::Es(Default::default()); let mut p = Parser::new( syntax, StringInput::new(text, BytePos(0), BytePos(text.len() as u32)), None, ); p.parse_module().unwrap() } fn has_top_level_await(text: &str) -> bool { let module = parse_module(text); contains_top_level_await(&module) } #[test] fn top_level_await_block() { assert!(has_top_level_await("if (maybe) { await test; }")) } #[test] fn top_level_await_for_of() { assert!(has_top_level_await("for await (let iter of []){}")) } #[test] fn top_level_export_await() { assert!(has_top_level_await("export const foo = await 1;")); assert!(has_top_level_await("export default await 1;")); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_utils/src/macros.rs
Rust
/// Shortcut for `quote_ident!(span.apply_mark(Mark::fresh(Mark::root())), s)` #[macro_export] macro_rules! private_ident { ($s:expr) => { private_ident!($crate::swc_common::DUMMY_SP, $s) }; ($span:expr, $s:expr) => {{ let mark = $crate::swc_common::Mark::new(); let ctxt = $crate::swc_common::SyntaxContext::empty().apply_mark(mark); $crate::swc_ecma_ast::Ident::new($s.into(), $span, ctxt) }}; } /// As we have multiple identifier types, the expected usage is /// `quote_ident!("foo").into()`. #[macro_export] macro_rules! quote_ident { ($s:expr) => {{ let sym: $crate::swc_atoms::Atom = $s.into(); let id: $crate::swc_ecma_ast::IdentName = sym.into(); id }}; ($ctxt:expr, $s:expr) => {{ let sym: $crate::swc_atoms::Atom = $s.into(); let id: $crate::swc_ecma_ast::Ident = $crate::swc_ecma_ast::Ident::new(sym, $crate::swc_common::DUMMY_SP, $ctxt); id }}; ($ctxt:expr, $span:expr, $s:expr) => {{ $crate::swc_ecma_ast::Ident::new($s.into(), $span, $ctxt) }}; } #[macro_export] macro_rules! quote_str { ($s:expr) => { quote_str!($crate::swc_common::DUMMY_SP, $s) }; ($span:expr, $s:expr) => {{ $crate::swc_ecma_ast::Str { span: $span, raw: None, value: $s.into(), } }}; } #[macro_export] macro_rules! quote_expr { ($span:expr, null) => {{ use $crate::swc_ecma_ast::*; Expr::Lit(Lit::Null(Null { span: $span })) }}; ($span:expr, undefined) => {{ box Expr::Ident(Ident::new("undefined", $span)) }}; } /// Creates a member expression. /// /// # Usage /// ```rust,ignore /// member_expr!(span, Function.bind.apply); /// ``` /// /// Returns Box<[Expr](swc_ecma_ast::Expr)>. #[macro_export] macro_rules! member_expr { ($ctxt:expr, $span:expr, $first:ident) => {{ use $crate::swc_ecma_ast::Expr; Box::new(Expr::Ident($crate::quote_ident!($ctxt, $span, stringify!($first)))) }}; ($ctxt:expr, $span:expr, $first:ident . $($rest:tt)+) => {{ let obj = member_expr!($ctxt, $span, $first); member_expr!(@EXT, $span, obj, $($rest)* ) }}; (@EXT, $span:expr, $obj:expr, $first:ident . $($rest:tt)* ) => {{ use $crate::swc_ecma_ast::MemberProp; use $crate::swc_ecma_ast::IdentName; let prop = MemberProp::Ident(IdentName::new(stringify!($first).into(), $span)); member_expr!(@EXT, $span, Box::new(Expr::Member(MemberExpr{ span: $crate::swc_common::DUMMY_SP, obj: $obj, prop, })), $($rest)*) }}; (@EXT, $span:expr, $obj:expr, $first:ident) => {{ use $crate::swc_ecma_ast::*; let prop = MemberProp::Ident(IdentName::new(stringify!($first).into(), $span)); MemberExpr{ span: $crate::swc_common::DUMMY_SP, obj: $obj, prop, } }}; } #[cfg(test)] mod tests { use swc_common::DUMMY_SP as span; use swc_ecma_ast::*; use crate::drop_span; #[test] fn quote_member_expr() { let expr: Box<Expr> = drop_span(member_expr!( Default::default(), Default::default(), Function.prototype.bind )) .into(); assert_eq!( expr, Box::new(Expr::Member(MemberExpr { span, obj: Box::new(Expr::Member(MemberExpr { span, obj: member_expr!(Default::default(), Default::default(), Function), prop: MemberProp::Ident("prototype".into()), })), prop: MemberProp::Ident("bind".into()), })) ); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_utils/src/node_ignore_span.rs
Rust
use std::{borrow::Cow, fmt::Debug, hash::Hash}; use swc_common::EqIgnoreSpan; use swc_ecma_ast::{Expr, MemberProp}; /// A newtype that will ignore Span while doing `eq` or `hash`. pub struct NodeIgnoringSpan<'a, Node: ToOwned + Debug>(Cow<'a, Node>); impl<Node: ToOwned + Debug> Debug for NodeIgnoringSpan<'_, Node> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple("NodeIgnoringSpan").field(&*self.0).finish() } } impl<'a, Node: ToOwned + Debug> NodeIgnoringSpan<'a, Node> { #[inline] pub fn borrowed(expr: &'a Node) -> Self { Self(Cow::Borrowed(expr)) } #[inline] pub fn owned(expr: <Node as ToOwned>::Owned) -> Self { Self(Cow::Owned(expr)) } } impl<Node: EqIgnoreSpan + ToOwned + Debug> PartialEq for NodeIgnoringSpan<'_, Node> { fn eq(&self, other: &Self) -> bool { self.0.eq_ignore_span(&other.0) } } impl<Node: EqIgnoreSpan + ToOwned + Debug> Eq for NodeIgnoringSpan<'_, Node> {} // TODO: This is only a workaround for Expr. we need something like // `hash_ignore_span` for each node in the end. impl Hash for NodeIgnoringSpan<'_, Expr> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { // In pratice, most of cases/input we are dealing with are Expr::Member or // Expr::Ident. match &*self.0 { Expr::Ident(i) => { i.sym.hash(state); } Expr::Member(i) => { { NodeIgnoringSpan::borrowed(i.obj.as_ref()).hash(state); } if let MemberProp::Ident(prop) = &i.prop { prop.sym.hash(state); } } _ => { // Other expression kinds would fallback to the same empty hash. // So, they will spend linear time to do comparisons. } } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_utils/src/number.rs
Rust
/// <https://tc39.es/ecma262/#sec-numeric-types-number-tostring> pub trait ToJsString { fn to_js_string(&self) -> String; } impl ToJsString for f64 { fn to_js_string(&self) -> String { let mut buffer = ryu_js::Buffer::new(); buffer.format(*self).to_string() } } #[derive(Debug, Clone, Copy, PartialEq)] pub struct JsNumber(f64); impl From<f64> for JsNumber { fn from(v: f64) -> Self { JsNumber(v) } } impl From<JsNumber> for f64 { fn from(v: JsNumber) -> Self { v.0 } } impl std::ops::Deref for JsNumber { type Target = f64; fn deref(&self) -> &Self::Target { &self.0 } } impl JsNumber { // https://tc39.es/ecma262/#sec-toint32 fn as_int32(&self) -> i32 { self.as_uint32() as i32 } // https://tc39.es/ecma262/#sec-touint32 fn as_uint32(&self) -> u32 { if !self.0.is_finite() { return 0; } // pow(2, 32) = 4294967296 self.0.trunc().rem_euclid(4294967296.0) as u32 } } // JsNumber + JsNumber impl std::ops::Add<JsNumber> for JsNumber { type Output = JsNumber; fn add(self, rhs: JsNumber) -> Self::Output { JsNumber(self.0 + rhs.0) } } // JsNumber - JsNumber impl std::ops::Sub<JsNumber> for JsNumber { type Output = JsNumber; fn sub(self, rhs: JsNumber) -> Self::Output { JsNumber(self.0 - rhs.0) } } // JsNumber * JsNumber impl std::ops::Mul<JsNumber> for JsNumber { type Output = JsNumber; fn mul(self, rhs: JsNumber) -> Self::Output { JsNumber(self.0 * rhs.0) } } // JsNumber / JsNumber impl std::ops::Div<JsNumber> for JsNumber { type Output = JsNumber; fn div(self, rhs: JsNumber) -> Self::Output { JsNumber(self.0 / rhs.0) } } // JsNumber % JsNumber impl std::ops::Rem<JsNumber> for JsNumber { type Output = JsNumber; fn rem(self, rhs: JsNumber) -> Self::Output { JsNumber(self.0 % rhs.0) } } // JsNumber ** JsNumber impl JsNumber { pub fn pow(self, rhs: JsNumber) -> JsNumber { // https://tc39.es/ecma262/multipage/ecmascript-data-types-and-values.html#sec-numeric-types-number-exponentiate // https://github.com/rust-lang/rust/issues/60468 if rhs.0.is_nan() { return JsNumber(f64::NAN); } if self.0.abs() == 1f64 && rhs.0.is_infinite() { return JsNumber(f64::NAN); } JsNumber(self.0.powf(rhs.0)) } } // JsNumber << JsNumber // https://tc39.es/ecma262/#sec-numeric-types-number-leftShift impl std::ops::Shl<JsNumber> for JsNumber { type Output = JsNumber; fn shl(self, rhs: JsNumber) -> Self::Output { JsNumber(self.as_int32().wrapping_shl(rhs.as_uint32()) as f64) } } // JsNumber >> JsNumber // https://tc39.es/ecma262/#sec-numeric-types-number-signedRightShift impl std::ops::Shr<JsNumber> for JsNumber { type Output = JsNumber; fn shr(self, rhs: JsNumber) -> Self::Output { JsNumber((self.as_int32()).wrapping_shr(rhs.as_uint32()) as f64) } } // JsNumber >>> JsNumber // https://tc39.es/ecma262/#sec-numeric-types-number-unsignedRightShift impl JsNumber { pub fn unsigned_shr(self, rhs: JsNumber) -> JsNumber { JsNumber((self.as_uint32()).wrapping_shr(rhs.as_uint32()) as f64) } } // JsNumber | JsNumber // https://tc39.es/ecma262/#sec-numberbitwiseop impl std::ops::BitOr<JsNumber> for JsNumber { type Output = JsNumber; fn bitor(self, rhs: JsNumber) -> Self::Output { JsNumber((self.as_int32() | rhs.as_int32()) as f64) } } // JsNumber & JsNumber // https://tc39.es/ecma262/#sec-numberbitwiseop impl std::ops::BitAnd<JsNumber> for JsNumber { type Output = JsNumber; fn bitand(self, rhs: JsNumber) -> Self::Output { JsNumber((self.as_int32() & rhs.as_int32()) as f64) } } // JsNumber ^ JsNumber // https://tc39.es/ecma262/#sec-numberbitwiseop impl std::ops::BitXor<JsNumber> for JsNumber { type Output = JsNumber; fn bitxor(self, rhs: JsNumber) -> Self::Output { JsNumber((self.as_int32() ^ rhs.as_int32()) as f64) } } // - JsNumber impl std::ops::Neg for JsNumber { type Output = JsNumber; fn neg(self) -> Self::Output { JsNumber(-self.0) } } // ~ JsNumber impl std::ops::Not for JsNumber { type Output = JsNumber; fn not(self) -> Self::Output { JsNumber(!(self.as_int32()) as f64) } } #[cfg(test)] mod test_js_number { use super::*; #[test] fn test_as_int32() { assert_eq!(JsNumber(f64::NAN).as_int32(), 0); assert_eq!(JsNumber(0.0).as_int32(), 0); assert_eq!(JsNumber(-0.0).as_int32(), 0); assert_eq!(JsNumber(f64::INFINITY).as_int32(), 0); assert_eq!(JsNumber(f64::NEG_INFINITY).as_int32(), 0); } #[test] fn test_as_uint32() { assert_eq!(JsNumber(f64::NAN).as_uint32(), 0); assert_eq!(JsNumber(0.0).as_uint32(), 0); assert_eq!(JsNumber(-0.0).as_uint32(), 0); assert_eq!(JsNumber(f64::INFINITY).as_uint32(), 0); assert_eq!(JsNumber(f64::NEG_INFINITY).as_uint32(), 0); assert_eq!(JsNumber(-8.0).as_uint32(), 4294967288); } #[test] fn test_add() { assert_eq!(JsNumber(1.0) + JsNumber(2.0), JsNumber(3.0)); assert!((JsNumber(1.0) + JsNumber(f64::NAN)).is_nan()); assert!((JsNumber(f64::NAN) + JsNumber(1.0)).is_nan()); assert!((JsNumber(f64::NAN) + JsNumber(f64::NAN)).is_nan()); assert!((JsNumber(f64::INFINITY) + JsNumber(f64::NEG_INFINITY)).is_nan()); assert!((JsNumber(f64::NEG_INFINITY) + JsNumber(f64::INFINITY)).is_nan()); assert_eq!( JsNumber(f64::INFINITY) + JsNumber(1.0), JsNumber(f64::INFINITY) ); assert_eq!( JsNumber(f64::NEG_INFINITY) + JsNumber(1.0), JsNumber(f64::NEG_INFINITY) ); assert_eq!(JsNumber(-0.0) + JsNumber(0.0), JsNumber(-0.0)); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_utils/src/parallel.rs
Rust
//! Module for parallel processing use once_cell::sync::Lazy; use swc_common::GLOBALS; use swc_ecma_ast::*; use swc_parallel::{ items::{IntoItems, Items}, join, }; static CPU_COUNT: Lazy<usize> = Lazy::new(num_cpus::get); pub fn cpu_count() -> usize { *CPU_COUNT } pub trait Parallel: swc_common::sync::Send + swc_common::sync::Sync { /// Used to create visitor. fn create(&self) -> Self; /// This can be called in anytime. fn merge(&mut self, other: Self); /// Invoked after visiting all [Stmt]s, possibly in parallel. /// /// /// Note: `visit_*_par` never calls this. fn after_stmts(&mut self, _stmts: &mut Vec<Stmt>) {} /// Invoked after visiting all [ModuleItem]s, possibly in parallel. /// /// /// Note: `visit_*_par` never calls this. fn after_module_items(&mut self, _stmts: &mut Vec<ModuleItem>) {} } pub trait ParallelExt: Parallel { /// Invoke `op` in parallel, if `swc_ecma_utils` is compiled with /// concurrent feature enabled and `nodes.len()` is bigger than threshold. /// /// /// This configures [GLOBALS], while not configuring [HANDLER] nor [HELPERS] fn maybe_par<I, F>(&mut self, threshold: usize, nodes: I, op: F) where I: IntoItems, F: Send + Sync + Fn(&mut Self, I::Elem), { self.maybe_par_idx(threshold, nodes, |v, _, n| op(v, n)) } /// Invoke `op` in parallel, if `swc_ecma_utils` is compiled with /// concurrent feature enabled and `nodes.len()` is bigger than threshold. /// /// /// This configures [GLOBALS], while not configuring [HANDLER] nor [HELPERS] fn maybe_par_idx<I, F>(&mut self, threshold: usize, nodes: I, op: F) where I: IntoItems, F: Send + Sync + Fn(&mut Self, usize, I::Elem), { self.maybe_par_idx_raw(threshold, nodes.into_items(), &op) } /// If you don't have a special reason, use [`ParallelExt::maybe_par`] or /// [`ParallelExt::maybe_par_idx`] instead. fn maybe_par_idx_raw<I, F>(&mut self, threshold: usize, nodes: I, op: &F) where I: Items, F: Send + Sync + Fn(&mut Self, usize, I::Elem); } #[cfg(feature = "concurrent")] impl<T> ParallelExt for T where T: Parallel, { fn maybe_par_idx_raw<I, F>(&mut self, threshold: usize, nodes: I, op: &F) where I: Items, F: Send + Sync + Fn(&mut Self, usize, I::Elem), { if nodes.len() >= threshold { GLOBALS.with(|globals| { let len = nodes.len(); if len == 0 { return; } if len == 1 { op(self, 0, nodes.into_iter().next().unwrap()); return; } let (na, nb) = nodes.split_at(len / 2); let mut vb = Parallel::create(&*self); let (_, vb) = join( || { GLOBALS.set(globals, || { self.maybe_par_idx_raw(threshold, na, op); }) }, || { GLOBALS.set(globals, || { vb.maybe_par_idx_raw(threshold, nb, op); vb }) }, ); Parallel::merge(self, vb); }); return; } for (idx, n) in nodes.into_iter().enumerate() { op(self, idx, n); } } } #[cfg(not(feature = "concurrent"))] impl<T> ParallelExt for T where T: Parallel, { fn maybe_par_idx_raw<I, F>(&mut self, _threshold: usize, nodes: I, op: &F) where I: Items, F: Send + Sync + Fn(&mut Self, usize, I::Elem), { for (idx, n) in nodes.into_iter().enumerate() { op(self, idx, n); } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_utils/src/stack_size.rs
Rust
/// Calls `callback` with a larger stack size. #[inline(always)] #[cfg(any( target_arch = "wasm32", target_arch = "arm", not(feature = "stacker"), // miri does not work with stacker miri ))] pub fn maybe_grow<R, F: FnOnce() -> R>(_red_zone: usize, _stack_size: usize, callback: F) -> R { callback() } /// Calls `callback` with a larger stack size. #[inline(always)] #[cfg(all( not(any(target_arch = "wasm32", target_arch = "arm", miri)), feature = "stacker" ))] pub fn maybe_grow<R, F: FnOnce() -> R>(red_zone: usize, stack_size: usize, callback: F) -> R { stacker::maybe_grow(red_zone, stack_size, callback) } /// Calls `callback` with a larger stack size. /// /// `maybe_grow` with default values. pub fn maybe_grow_default<R, F: FnOnce() -> R>(callback: F) -> R { let (red_zone, stack_size) = (4 * 1024, 16 * 1024); maybe_grow(red_zone, stack_size, callback) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_utils/src/value.rs
Rust
use std::ops::Not; use self::Value::{Known, Unknown}; /// Runtime value. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Value<T> { Known(T), /// Not determined at compile time.` Unknown, } /// Type of value. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Type { Undefined, Null, Bool, Str, Symbol, Num, Obj, } impl Value<Type> { pub fn casted_to_number_on_add(self) -> bool { match self { Known(Type::Bool) | Known(Type::Null) | Known(Type::Num) | Known(Type::Undefined) => { true } _ => false, } } } /// Value could not be determined pub struct UnknownError; // impl<T> Try for Value<T> { // type Ok = T; // type Error = UnknownError; // fn from_ok(t: T) -> Self { // Known(t) // } // fn from_error(_: UnknownError) -> Self { // Unknown // } // fn into_result(self) -> Result<T, UnknownError> { // match self { // Known(t) => Ok(t), // Unknown => Err(UnknownError), // } // } // } impl<T> Value<T> { pub fn into_result(self) -> Result<T, UnknownError> { match self { Known(v) => Ok(v), Unknown => Err(UnknownError), } } } impl<T> Value<T> { /// Returns true if the value is not known. pub fn is_unknown(&self) -> bool { matches!(*self, Unknown) } /// Returns true if the value is known. pub fn is_known(&self) -> bool { matches!(*self, Known(..)) } } impl Value<bool> { pub fn and(self, other: Self) -> Self { match self { Known(true) => other, Known(false) => Known(false), Unknown => match other { Known(false) => Known(false), _ => Unknown, }, } } pub fn or(self, other: Self) -> Self { match self { Known(true) => Known(true), Known(false) => other, Unknown => match other { Known(true) => Known(true), _ => Unknown, }, } } } impl Not for Value<bool> { type Output = Self; fn not(self) -> Self { match self { Value::Known(b) => Value::Known(!b), Value::Unknown => Value::Unknown, } } } pub trait Merge { fn merge(&mut self, rhs: Self); } impl Merge for Option<Value<Type>> { fn merge(&mut self, rhs: Self) { *self = match (*self, rhs) { (None, None) => None, (None, Some(ty)) | (Some(ty), None) => Some(ty), (Some(ty1), Some(ty2)) if ty1 == ty2 => Some(ty1), _ => Some(Unknown), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_utils/src/var.rs
Rust
use swc_ecma_ast::*; use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; use crate::ident::IdentLike; /// This collects variables bindings while ignoring if it's nested in /// expression. pub struct VarCollector<'a, I: IdentLike> { pub to: &'a mut Vec<I>, } impl<I: IdentLike> Visit for VarCollector<'_, I> { noop_visit_type!(fail); fn visit_arrow_expr(&mut self, _: &ArrowExpr) {} fn visit_constructor(&mut self, _: &Constructor) {} fn visit_expr(&mut self, _: &Expr) {} fn visit_function(&mut self, _: &Function) {} fn visit_key_value_pat_prop(&mut self, node: &KeyValuePatProp) { node.value.visit_with(self); } fn visit_ident(&mut self, i: &Ident) { self.to.push(I::from_ident(i)) } fn visit_var_declarator(&mut self, node: &VarDeclarator) { node.name.visit_with(self); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_visit/src/lib.rs
Rust
// This is not a public api. #![cfg_attr(docsrs, feature(doc_cfg))] #![deny(clippy::all)] #![allow(clippy::ptr_arg)] #[doc(hidden)] pub extern crate swc_ecma_ast; use std::{borrow::Cow, fmt::Debug}; use swc_common::{pass::CompilerPass, util::take::Take, Span, DUMMY_SP}; use swc_ecma_ast::*; use swc_visit::{Repeat, Repeated}; pub use crate::generated::*; mod generated; pub fn fold_pass<V>(pass: V) -> FoldPass<V> where V: Fold, { FoldPass { pass } } pub struct FoldPass<V> { pass: V, } impl<V> Pass for FoldPass<V> where V: Fold, { #[inline(always)] fn process(&mut self, program: &mut Program) { program.map_with_mut(|p| p.fold_with(&mut self.pass)); } } impl<V> Fold for FoldPass<V> where V: Fold, { #[inline(always)] fn fold_program(&mut self, node: Program) -> Program { self.pass.fold_program(node) } #[inline(always)] fn fold_module(&mut self, node: Module) -> Module { self.pass.fold_module(node) } #[inline(always)] fn fold_script(&mut self, node: Script) -> Script { self.pass.fold_script(node) } #[inline(always)] fn fold_stmt(&mut self, node: Stmt) -> Stmt { self.pass.fold_stmt(node) } #[inline(always)] fn fold_module_item(&mut self, item: ModuleItem) -> ModuleItem { self.pass.fold_module_item(item) } #[inline(always)] fn fold_expr(&mut self, expr: Expr) -> Expr { self.pass.fold_expr(expr) } #[inline(always)] fn fold_pat(&mut self, pat: Pat) -> Pat { self.pass.fold_pat(pat) } #[inline(always)] fn fold_assign_target(&mut self, target: AssignTarget) -> AssignTarget { self.pass.fold_assign_target(target) } #[inline(always)] fn fold_ident(&mut self, ident: Ident) -> Ident { self.pass.fold_ident(ident) } } impl<V> Repeated for FoldPass<V> where V: Fold + Repeated, { fn changed(&self) -> bool { self.pass.changed() } fn reset(&mut self) { self.pass.reset(); } } impl<V> CompilerPass for FoldPass<V> where V: Fold + CompilerPass, { fn name(&self) -> Cow<'static, str> { self.pass.name() } } pub fn visit_mut_pass<V>(pass: V) -> VisitMutPass<V> where V: VisitMut, { VisitMutPass { pass } } pub struct VisitMutPass<V> { pass: V, } impl<V> Pass for VisitMutPass<V> where V: VisitMut, { #[inline(always)] fn process(&mut self, program: &mut Program) { program.visit_mut_with(&mut self.pass); } } impl<V> VisitMut for VisitMutPass<V> where V: VisitMut, { #[inline(always)] fn visit_mut_program(&mut self, program: &mut Program) { self.pass.visit_mut_program(program); } #[inline(always)] fn visit_mut_module(&mut self, module: &mut Module) { self.pass.visit_mut_module(module); } #[inline(always)] fn visit_mut_script(&mut self, script: &mut Script) { self.pass.visit_mut_script(script); } #[inline(always)] fn visit_mut_module_item(&mut self, item: &mut ModuleItem) { self.pass.visit_mut_module_item(item); } #[inline(always)] fn visit_mut_stmt(&mut self, stmt: &mut Stmt) { self.pass.visit_mut_stmt(stmt); } #[inline(always)] fn visit_mut_expr(&mut self, expr: &mut Expr) { self.pass.visit_mut_expr(expr); } #[inline(always)] fn visit_mut_pat(&mut self, pat: &mut Pat) { self.pass.visit_mut_pat(pat); } #[inline(always)] fn visit_mut_assign_target(&mut self, target: &mut AssignTarget) { self.pass.visit_mut_assign_target(target); } #[inline(always)] fn visit_mut_ident(&mut self, ident: &mut Ident) { self.pass.visit_mut_ident(ident); } } impl<V> Repeated for VisitMutPass<V> where V: VisitMut + Repeated, { fn changed(&self) -> bool { self.pass.changed() } fn reset(&mut self) { self.pass.reset(); } } impl<V> CompilerPass for VisitMutPass<V> where V: VisitMut + CompilerPass, { fn name(&self) -> Cow<'static, str> { self.pass.name() } } pub fn visit_pass<V>(pass: V) -> VisitPass<V> where V: Visit, { VisitPass { pass } } pub struct VisitPass<V> { pass: V, } impl<V> Pass for VisitPass<V> where V: Visit, { #[inline(always)] fn process(&mut self, program: &mut Program) { program.visit_with(&mut self.pass); } } impl<V> Repeated for VisitPass<V> where V: Visit + Repeated, { fn changed(&self) -> bool { self.pass.changed() } fn reset(&mut self) { self.pass.reset(); } } impl<V> CompilerPass for VisitPass<V> where V: Visit + CompilerPass, { fn name(&self) -> Cow<'static, str> { self.pass.name() } } impl<V> Fold for Repeat<V> where V: Fold + Repeated, { fn fold_program(&mut self, mut node: Program) -> Program { loop { self.pass.reset(); node = node.fold_with(&mut self.pass); if !self.pass.changed() { break; } } node } fn fold_module(&mut self, mut node: Module) -> Module { loop { self.pass.reset(); node = node.fold_with(&mut self.pass); if !self.pass.changed() { break; } } node } fn fold_script(&mut self, mut node: Script) -> Script { loop { self.pass.reset(); node = node.fold_with(&mut self.pass); if !self.pass.changed() { break; } } node } } impl<V> VisitMut for Repeat<V> where V: VisitMut + Repeated, { fn visit_mut_program(&mut self, node: &mut Program) { loop { self.pass.reset(); node.visit_mut_with(&mut self.pass); if !self.pass.changed() { break; } } } fn visit_mut_module(&mut self, node: &mut Module) { loop { self.pass.reset(); node.visit_mut_with(&mut self.pass); if !self.pass.changed() { break; } } } fn visit_mut_script(&mut self, node: &mut Script) { loop { self.pass.reset(); node.visit_mut_with(&mut self.pass); if !self.pass.changed() { break; } } } } /// Not a public api. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] struct SpanRemover; /// Returns a `Fold` which changes all span into `DUMMY_SP`. pub fn span_remover() -> impl Debug + Fold + Copy + Eq + Default + 'static { SpanRemover } impl Fold for SpanRemover { fn fold_span(&mut self, _: Span) -> Span { DUMMY_SP } } #[macro_export] macro_rules! assert_eq_ignore_span { ($l:expr, $r:expr) => {{ use $crate::FoldWith; let l = $l.fold_with(&mut $crate::span_remover()); let r = $r.fold_with(&mut $crate::span_remover()); assert_eq!(l, r); }}; ($l:expr, $r:expr, $($tts:tt)*) => {{ use $crate::FoldWith; let l = $l.fold_with(&mut $crate::span_remover()); let r = $r.fold_with(&mut $crate::span_remover()); assert_eq!(l, r, $($tts)*); }}; } /// Implemented for passes which inject variables. /// /// If a pass depends on other pass which injects variables, this trait can be /// used to keep the variables. pub trait InjectVars { fn take_vars(&mut self) -> Vec<VarDeclarator>; } impl<V> InjectVars for FoldPass<V> where V: Fold + InjectVars, { fn take_vars(&mut self) -> Vec<VarDeclarator> { self.pass.take_vars() } } impl<V> InjectVars for VisitMutPass<V> where V: VisitMut + InjectVars, { fn take_vars(&mut self) -> Vec<VarDeclarator> { self.pass.take_vars() } } impl<V> InjectVars for VisitPass<V> where V: Visit + InjectVars, { fn take_vars(&mut self) -> Vec<VarDeclarator> { self.pass.take_vars() } } /// Note: Ignoring more types is not considered as a breaking change. #[macro_export] macro_rules! noop_fold_type { ($name:ident, $N:tt) => { fn $name(&mut self, node: $crate::swc_ecma_ast::$N) -> $crate::swc_ecma_ast::$N { node } }; () => { noop_fold_type!(fold_accessibility, Accessibility); noop_fold_type!(fold_true_plus_minus, TruePlusMinus); noop_fold_type!(fold_ts_array_type, TsArrayType); noop_fold_type!(fold_ts_call_signature_decl, TsCallSignatureDecl); noop_fold_type!(fold_ts_conditional_type, TsConditionalType); noop_fold_type!(fold_ts_construct_signature_decl, TsConstructSignatureDecl); noop_fold_type!(fold_ts_constructor_type, TsConstructorType); noop_fold_type!(fold_ts_entity_name, TsEntityName); noop_fold_type!(fold_ts_enum_decl, TsEnumDecl); noop_fold_type!(fold_ts_enum_member, TsEnumMember); noop_fold_type!(fold_ts_enum_member_id, TsEnumMemberId); noop_fold_type!(fold_ts_expr_with_type_args, TsExprWithTypeArgs); noop_fold_type!(fold_ts_fn_or_constructor_type, TsFnOrConstructorType); noop_fold_type!(fold_ts_fn_param, TsFnParam); noop_fold_type!(fold_ts_fn_type, TsFnType); noop_fold_type!(fold_ts_import_equals_decl, TsImportEqualsDecl); noop_fold_type!(fold_ts_import_type, TsImportType); noop_fold_type!(fold_ts_index_signature, TsIndexSignature); noop_fold_type!(fold_ts_indexed_access_type, TsIndexedAccessType); noop_fold_type!(fold_ts_infer_type, TsInferType); noop_fold_type!(fold_ts_interface_body, TsInterfaceBody); noop_fold_type!(fold_ts_interface_decl, TsInterfaceDecl); noop_fold_type!(fold_ts_intersection_type, TsIntersectionType); noop_fold_type!(fold_ts_keyword_type, TsKeywordType); noop_fold_type!(fold_ts_keyword_type_kind, TsKeywordTypeKind); noop_fold_type!(fold_ts_mapped_type, TsMappedType); noop_fold_type!(fold_ts_method_signature, TsMethodSignature); noop_fold_type!(fold_ts_module_block, TsModuleBlock); noop_fold_type!(fold_ts_module_decl, TsModuleDecl); noop_fold_type!(fold_ts_module_name, TsModuleName); noop_fold_type!(fold_ts_namespace_body, TsNamespaceBody); noop_fold_type!(fold_ts_namespace_decl, TsNamespaceDecl); noop_fold_type!(fold_ts_namespace_export_decl, TsNamespaceExportDecl); noop_fold_type!(fold_ts_optional_type, TsOptionalType); noop_fold_type!(fold_ts_param_prop, TsParamProp); noop_fold_type!(fold_ts_param_prop_param, TsParamPropParam); noop_fold_type!(fold_ts_parenthesized_type, TsParenthesizedType); noop_fold_type!(fold_ts_property_signature, TsPropertySignature); noop_fold_type!(fold_ts_qualified_name, TsQualifiedName); noop_fold_type!(fold_ts_rest_type, TsRestType); noop_fold_type!(fold_ts_this_type, TsThisType); noop_fold_type!(fold_ts_this_type_or_ident, TsThisTypeOrIdent); noop_fold_type!(fold_ts_tuple_type, TsTupleType); noop_fold_type!(fold_ts_type, TsType); noop_fold_type!(fold_ts_type_alias_decl, TsTypeAliasDecl); noop_fold_type!(fold_ts_type_ann, TsTypeAnn); noop_fold_type!(fold_ts_type_assertion, TsTypeAssertion); noop_fold_type!(fold_ts_type_element, TsTypeElement); noop_fold_type!(fold_ts_type_lit, TsTypeLit); noop_fold_type!(fold_ts_type_operator, TsTypeOperator); noop_fold_type!(fold_ts_type_operator_op, TsTypeOperatorOp); noop_fold_type!(fold_ts_type_param, TsTypeParam); noop_fold_type!(fold_ts_type_param_decl, TsTypeParamDecl); noop_fold_type!(fold_ts_type_param_instantiation, TsTypeParamInstantiation); noop_fold_type!(fold_ts_type_predicate, TsTypePredicate); noop_fold_type!(fold_ts_type_query, TsTypeQuery); noop_fold_type!(fold_ts_type_query_expr, TsTypeQueryExpr); noop_fold_type!(fold_ts_type_ref, TsTypeRef); noop_fold_type!( fold_ts_union_or_intersection_type, TsUnionOrIntersectionType ); noop_fold_type!(fold_ts_union_type, TsUnionType); }; } /// Note: Ignoring more types is not considered as a breaking change. #[macro_export] macro_rules! noop_visit_type { (fail) => { noop_visit_type!(visit_accessibility, Accessibility, fail); noop_visit_type!(visit_true_plus_minus, TruePlusMinus, fail); noop_visit_type!(visit_ts_array_type, TsArrayType, fail); noop_visit_type!(visit_ts_call_signature_decl, TsCallSignatureDecl, fail); noop_visit_type!(visit_ts_conditional_type, TsConditionalType, fail); noop_visit_type!( visit_ts_construct_signature_decl, TsConstructSignatureDecl, fail ); noop_visit_type!(visit_ts_constructor_type, TsConstructorType, fail); noop_visit_type!(visit_ts_entity_name, TsEntityName, fail); noop_visit_type!(visit_ts_expr_with_type_args, TsExprWithTypeArgs, fail); noop_visit_type!(visit_ts_fn_or_constructor_type, TsFnOrConstructorType, fail); noop_visit_type!(visit_ts_fn_param, TsFnParam, fail); noop_visit_type!(visit_ts_fn_type, TsFnType, fail); noop_visit_type!(visit_ts_import_type, TsImportType, fail); noop_visit_type!(visit_ts_index_signature, TsIndexSignature, fail); noop_visit_type!(visit_ts_indexed_access_type, TsIndexedAccessType, fail); noop_visit_type!(visit_ts_infer_type, TsInferType, fail); noop_visit_type!(visit_ts_interface_body, TsInterfaceBody, fail); noop_visit_type!(visit_ts_interface_decl, TsInterfaceDecl, fail); noop_visit_type!(visit_ts_intersection_type, TsIntersectionType, fail); noop_visit_type!(visit_ts_keyword_type, TsKeywordType, fail); noop_visit_type!(visit_ts_keyword_type_kind, TsKeywordTypeKind, fail); noop_visit_type!(visit_ts_mapped_type, TsMappedType, fail); noop_visit_type!(visit_ts_method_signature, TsMethodSignature, fail); noop_visit_type!(visit_ts_optional_type, TsOptionalType, fail); noop_visit_type!(visit_ts_parenthesized_type, TsParenthesizedType, fail); noop_visit_type!(visit_ts_property_signature, TsPropertySignature, fail); noop_visit_type!(visit_ts_qualified_name, TsQualifiedName, fail); noop_visit_type!(visit_ts_rest_type, TsRestType, fail); noop_visit_type!(visit_ts_this_type, TsThisType, fail); noop_visit_type!(visit_ts_this_type_or_ident, TsThisTypeOrIdent, fail); noop_visit_type!(visit_ts_tuple_type, TsTupleType, fail); noop_visit_type!(visit_ts_type, TsType, fail); noop_visit_type!(visit_ts_type_alias_decl, TsTypeAliasDecl, fail); noop_visit_type!(visit_ts_type_ann, TsTypeAnn, fail); noop_visit_type!(visit_ts_type_element, TsTypeElement, fail); noop_visit_type!(visit_ts_type_lit, TsTypeLit, fail); noop_visit_type!(visit_ts_type_operator, TsTypeOperator, fail); noop_visit_type!(visit_ts_type_operator_op, TsTypeOperatorOp, fail); noop_visit_type!(visit_ts_type_param, TsTypeParam, fail); noop_visit_type!(visit_ts_type_param_decl, TsTypeParamDecl, fail); noop_visit_type!( visit_ts_type_param_instantiation, TsTypeParamInstantiation, fail ); noop_visit_type!(visit_ts_type_predicate, TsTypePredicate, fail); noop_visit_type!(visit_ts_type_query, TsTypeQuery, fail); noop_visit_type!(visit_ts_type_query_expr, TsTypeQueryExpr, fail); noop_visit_type!(visit_ts_type_ref, TsTypeRef, fail); noop_visit_type!( visit_ts_union_or_intersection_type, TsUnionOrIntersectionType, fail ); noop_visit_type!(visit_ts_union_type, TsUnionType, fail); }; () => { noop_visit_type!(visit_accessibility, Accessibility); noop_visit_type!(visit_true_plus_minus, TruePlusMinus); noop_visit_type!(visit_ts_array_type, TsArrayType); noop_visit_type!(visit_ts_call_signature_decl, TsCallSignatureDecl); noop_visit_type!(visit_ts_conditional_type, TsConditionalType); noop_visit_type!(visit_ts_construct_signature_decl, TsConstructSignatureDecl); noop_visit_type!(visit_ts_constructor_type, TsConstructorType); noop_visit_type!(visit_ts_entity_name, TsEntityName); noop_visit_type!(visit_ts_expr_with_type_args, TsExprWithTypeArgs); noop_visit_type!(visit_ts_fn_or_constructor_type, TsFnOrConstructorType); noop_visit_type!(visit_ts_fn_param, TsFnParam); noop_visit_type!(visit_ts_fn_type, TsFnType); noop_visit_type!(visit_ts_import_type, TsImportType); noop_visit_type!(visit_ts_index_signature, TsIndexSignature); noop_visit_type!(visit_ts_indexed_access_type, TsIndexedAccessType); noop_visit_type!(visit_ts_infer_type, TsInferType); noop_visit_type!(visit_ts_interface_body, TsInterfaceBody); noop_visit_type!(visit_ts_interface_decl, TsInterfaceDecl); noop_visit_type!(visit_ts_intersection_type, TsIntersectionType); noop_visit_type!(visit_ts_keyword_type, TsKeywordType); noop_visit_type!(visit_ts_keyword_type_kind, TsKeywordTypeKind); noop_visit_type!(visit_ts_mapped_type, TsMappedType); noop_visit_type!(visit_ts_method_signature, TsMethodSignature); noop_visit_type!(visit_ts_optional_type, TsOptionalType); noop_visit_type!(visit_ts_parenthesized_type, TsParenthesizedType); noop_visit_type!(visit_ts_property_signature, TsPropertySignature); noop_visit_type!(visit_ts_qualified_name, TsQualifiedName); noop_visit_type!(visit_ts_rest_type, TsRestType); noop_visit_type!(visit_ts_this_type, TsThisType); noop_visit_type!(visit_ts_this_type_or_ident, TsThisTypeOrIdent); noop_visit_type!(visit_ts_tuple_type, TsTupleType); noop_visit_type!(visit_ts_type, TsType); noop_visit_type!(visit_ts_type_alias_decl, TsTypeAliasDecl); noop_visit_type!(visit_ts_type_ann, TsTypeAnn); noop_visit_type!(visit_ts_type_element, TsTypeElement); noop_visit_type!(visit_ts_type_lit, TsTypeLit); noop_visit_type!(visit_ts_type_operator, TsTypeOperator); noop_visit_type!(visit_ts_type_operator_op, TsTypeOperatorOp); noop_visit_type!(visit_ts_type_param, TsTypeParam); noop_visit_type!(visit_ts_type_param_decl, TsTypeParamDecl); noop_visit_type!(visit_ts_type_param_instantiation, TsTypeParamInstantiation); noop_visit_type!(visit_ts_type_predicate, TsTypePredicate); noop_visit_type!(visit_ts_type_query, TsTypeQuery); noop_visit_type!(visit_ts_type_query_expr, TsTypeQueryExpr); noop_visit_type!(visit_ts_type_ref, TsTypeRef); noop_visit_type!( visit_ts_union_or_intersection_type, TsUnionOrIntersectionType ); noop_visit_type!(visit_ts_union_type, TsUnionType); }; ($name:ident, $N:tt, fail) => { #[cfg_attr(not(debug_assertions), inline(always))] fn $name(&mut self, _: &$crate::swc_ecma_ast::$N) { $crate::fail_no_typescript(stringify!($name)); } }; ($name:ident, $N:tt) => { fn $name(&mut self, _: &$crate::swc_ecma_ast::$N) {} }; } /// NOT A PUBLIC API #[doc(hidden)] #[cfg_attr(not(debug_assertions), inline(always))] pub fn fail_not_standard() { unsafe { debug_unreachable::debug_unreachable!( "This visitor supports only standard ECMAScript types. This method fails for \ optimization purpose." ) } } /// NOT A PUBLIC API #[doc(hidden)] #[cfg_attr(not(debug_assertions), inline(always))] pub fn fail_no_typescript(visitor_name: &str) { unsafe { debug_unreachable::debug_unreachable!( "This visitor does not support TypeScript. This method fails for optimization \ purposes. Encountered in unreachable visitor: {visitor_name}" ) } } /// Mark visitor as ECMAScript standard only and mark other types as /// unreachable. /// /// Used to reduce the binary size. #[macro_export] macro_rules! standard_only_fold { ($name:ident, $N:ident) => { fn $name(&mut self, n: $crate::swc_ecma_ast::$N) -> $crate::swc_ecma_ast::$N { $crate::fail_not_standard(); n } }; () => { standard_only_fold!(fold_accessibility, Accessibility); standard_only_fold!(fold_true_plus_minus, TruePlusMinus); standard_only_fold!(fold_ts_array_type, TsArrayType); standard_only_fold!(fold_ts_call_signature_decl, TsCallSignatureDecl); standard_only_fold!(fold_ts_conditional_type, TsConditionalType); standard_only_fold!(fold_ts_construct_signature_decl, TsConstructSignatureDecl); standard_only_fold!(fold_ts_constructor_type, TsConstructorType); standard_only_fold!(fold_ts_entity_name, TsEntityName); standard_only_fold!(fold_ts_expr_with_type_args, TsExprWithTypeArgs); standard_only_fold!(fold_ts_fn_or_constructor_type, TsFnOrConstructorType); standard_only_fold!(fold_ts_fn_param, TsFnParam); standard_only_fold!(fold_ts_fn_type, TsFnType); standard_only_fold!(fold_ts_import_type, TsImportType); standard_only_fold!(fold_ts_index_signature, TsIndexSignature); standard_only_fold!(fold_ts_indexed_access_type, TsIndexedAccessType); standard_only_fold!(fold_ts_infer_type, TsInferType); standard_only_fold!(fold_ts_interface_body, TsInterfaceBody); standard_only_fold!(fold_ts_interface_decl, TsInterfaceDecl); standard_only_fold!(fold_ts_intersection_type, TsIntersectionType); standard_only_fold!(fold_ts_keyword_type, TsKeywordType); standard_only_fold!(fold_ts_keyword_type_kind, TsKeywordTypeKind); standard_only_fold!(fold_ts_mapped_type, TsMappedType); standard_only_fold!(fold_ts_method_signature, TsMethodSignature); standard_only_fold!(fold_ts_optional_type, TsOptionalType); standard_only_fold!(fold_ts_parenthesized_type, TsParenthesizedType); standard_only_fold!(fold_ts_property_signature, TsPropertySignature); standard_only_fold!(fold_ts_qualified_name, TsQualifiedName); standard_only_fold!(fold_ts_rest_type, TsRestType); standard_only_fold!(fold_ts_this_type, TsThisType); standard_only_fold!(fold_ts_this_type_or_ident, TsThisTypeOrIdent); standard_only_fold!(fold_ts_tuple_type, TsTupleType); standard_only_fold!(fold_ts_type, TsType); standard_only_fold!(fold_ts_type_alias_decl, TsTypeAliasDecl); standard_only_fold!(fold_ts_type_ann, TsTypeAnn); standard_only_fold!(fold_ts_type_element, TsTypeElement); standard_only_fold!(fold_ts_type_lit, TsTypeLit); standard_only_fold!(fold_ts_type_operator, TsTypeOperator); standard_only_fold!(fold_ts_type_operator_op, TsTypeOperatorOp); standard_only_fold!(fold_ts_type_param, TsTypeParam); standard_only_fold!(fold_ts_type_param_decl, TsTypeParamDecl); standard_only_fold!(fold_ts_type_param_instantiation, TsTypeParamInstantiation); standard_only_fold!(fold_ts_type_predicate, TsTypePredicate); standard_only_fold!(fold_ts_type_query, TsTypeQuery); standard_only_fold!(fold_ts_type_query_expr, TsTypeQueryExpr); standard_only_fold!(fold_ts_type_ref, TsTypeRef); standard_only_fold!( fold_ts_union_or_intersection_type, TsUnionOrIntersectionType ); standard_only_fold!(fold_ts_union_type, TsUnionType); standard_only_fold!(fold_jsx_element, JSXElement); standard_only_fold!(fold_jsx_fragment, JSXFragment); standard_only_fold!(fold_jsx_empty_expr, JSXEmptyExpr); standard_only_fold!(fold_jsx_member_expr, JSXMemberExpr); standard_only_fold!(fold_jsx_namespaced_name, JSXNamespacedName); }; } /// Mark visitor as ECMAScript standard only and mark other types as /// unreachable. /// /// Used to reduce the binary size. #[macro_export] macro_rules! standard_only_visit { ($name:ident, $N:ident) => { fn $name(&mut self, _: &$crate::swc_ecma_ast::$N) { $crate::fail_not_standard() } }; () => { standard_only_visit!(visit_accessibility, Accessibility); standard_only_visit!(visit_true_plus_minus, TruePlusMinus); standard_only_visit!(visit_ts_array_type, TsArrayType); standard_only_visit!(visit_ts_call_signature_decl, TsCallSignatureDecl); standard_only_visit!(visit_ts_conditional_type, TsConditionalType); standard_only_visit!(visit_ts_construct_signature_decl, TsConstructSignatureDecl); standard_only_visit!(visit_ts_constructor_type, TsConstructorType); standard_only_visit!(visit_ts_entity_name, TsEntityName); standard_only_visit!(visit_ts_expr_with_type_args, TsExprWithTypeArgs); standard_only_visit!(visit_ts_fn_or_constructor_type, TsFnOrConstructorType); standard_only_visit!(visit_ts_fn_param, TsFnParam); standard_only_visit!(visit_ts_fn_type, TsFnType); standard_only_visit!(visit_ts_import_type, TsImportType); standard_only_visit!(visit_ts_index_signature, TsIndexSignature); standard_only_visit!(visit_ts_indexed_access_type, TsIndexedAccessType); standard_only_visit!(visit_ts_infer_type, TsInferType); standard_only_visit!(visit_ts_interface_body, TsInterfaceBody); standard_only_visit!(visit_ts_interface_decl, TsInterfaceDecl); standard_only_visit!(visit_ts_intersection_type, TsIntersectionType); standard_only_visit!(visit_ts_keyword_type, TsKeywordType); standard_only_visit!(visit_ts_keyword_type_kind, TsKeywordTypeKind); standard_only_visit!(visit_ts_mapped_type, TsMappedType); standard_only_visit!(visit_ts_method_signature, TsMethodSignature); standard_only_visit!(visit_ts_optional_type, TsOptionalType); standard_only_visit!(visit_ts_parenthesized_type, TsParenthesizedType); standard_only_visit!(visit_ts_property_signature, TsPropertySignature); standard_only_visit!(visit_ts_qualified_name, TsQualifiedName); standard_only_visit!(visit_ts_rest_type, TsRestType); standard_only_visit!(visit_ts_this_type, TsThisType); standard_only_visit!(visit_ts_this_type_or_ident, TsThisTypeOrIdent); standard_only_visit!(visit_ts_tuple_type, TsTupleType); standard_only_visit!(visit_ts_type, TsType); standard_only_visit!(visit_ts_type_alias_decl, TsTypeAliasDecl); standard_only_visit!(visit_ts_type_ann, TsTypeAnn); standard_only_visit!(visit_ts_type_element, TsTypeElement); standard_only_visit!(visit_ts_type_lit, TsTypeLit); standard_only_visit!(visit_ts_type_operator, TsTypeOperator); standard_only_visit!(visit_ts_type_operator_op, TsTypeOperatorOp); standard_only_visit!(visit_ts_type_param, TsTypeParam); standard_only_visit!(visit_ts_type_param_decl, TsTypeParamDecl); standard_only_visit!(visit_ts_type_param_instantiation, TsTypeParamInstantiation); standard_only_visit!(visit_ts_type_predicate, TsTypePredicate); standard_only_visit!(visit_ts_type_query, TsTypeQuery); standard_only_visit!(visit_ts_type_query_expr, TsTypeQueryExpr); standard_only_visit!(visit_ts_type_ref, TsTypeRef); standard_only_visit!( visit_ts_union_or_intersection_type, TsUnionOrIntersectionType ); standard_only_visit!(visit_ts_union_type, TsUnionType); standard_only_visit!(visit_jsx_element, JSXElement); standard_only_visit!(visit_jsx_fragment, JSXFragment); standard_only_visit!(visit_jsx_empty_expr, JSXEmptyExpr); standard_only_visit!(visit_jsx_member_expr, JSXMemberExpr); standard_only_visit!(visit_jsx_namespaced_name, JSXNamespacedName); }; } /// Mark visitor as ECMAScript standard only and mark other types as /// unreachable. /// /// Used to reduce the binary size. #[macro_export] macro_rules! standard_only_visit_mut { ($name:ident, $N:ident) => { fn $name(&mut self, _: &mut $crate::swc_ecma_ast::$N) { $crate::fail_not_standard() } }; () => { standard_only_visit_mut!(visit_mut_accessibility, Accessibility); standard_only_visit_mut!(visit_mut_true_plus_minus, TruePlusMinus); standard_only_visit_mut!(visit_mut_ts_array_type, TsArrayType); standard_only_visit_mut!(visit_mut_ts_call_signature_decl, TsCallSignatureDecl); standard_only_visit_mut!(visit_mut_ts_conditional_type, TsConditionalType); standard_only_visit_mut!( visit_mut_ts_construct_signature_decl, TsConstructSignatureDecl ); standard_only_visit_mut!(visit_mut_ts_constructor_type, TsConstructorType); standard_only_visit_mut!(visit_mut_ts_entity_name, TsEntityName); standard_only_visit_mut!(visit_mut_ts_expr_with_type_args, TsExprWithTypeArgs); standard_only_visit_mut!(visit_mut_ts_fn_or_constructor_type, TsFnOrConstructorType); standard_only_visit_mut!(visit_mut_ts_fn_param, TsFnParam); standard_only_visit_mut!(visit_mut_ts_fn_type, TsFnType); standard_only_visit_mut!(visit_mut_ts_import_type, TsImportType); standard_only_visit_mut!(visit_mut_ts_index_signature, TsIndexSignature); standard_only_visit_mut!(visit_mut_ts_indexed_access_type, TsIndexedAccessType); standard_only_visit_mut!(visit_mut_ts_infer_type, TsInferType); standard_only_visit_mut!(visit_mut_ts_interface_body, TsInterfaceBody); standard_only_visit_mut!(visit_mut_ts_interface_decl, TsInterfaceDecl); standard_only_visit_mut!(visit_mut_ts_intersection_type, TsIntersectionType); standard_only_visit_mut!(visit_mut_ts_keyword_type, TsKeywordType); standard_only_visit_mut!(visit_mut_ts_keyword_type_kind, TsKeywordTypeKind); standard_only_visit_mut!(visit_mut_ts_mapped_type, TsMappedType); standard_only_visit_mut!(visit_mut_ts_method_signature, TsMethodSignature); standard_only_visit_mut!(visit_mut_ts_optional_type, TsOptionalType); standard_only_visit_mut!(visit_mut_ts_parenthesized_type, TsParenthesizedType); standard_only_visit_mut!(visit_mut_ts_property_signature, TsPropertySignature); standard_only_visit_mut!(visit_mut_ts_qualified_name, TsQualifiedName); standard_only_visit_mut!(visit_mut_ts_rest_type, TsRestType); standard_only_visit_mut!(visit_mut_ts_this_type, TsThisType); standard_only_visit_mut!(visit_mut_ts_this_type_or_ident, TsThisTypeOrIdent); standard_only_visit_mut!(visit_mut_ts_tuple_type, TsTupleType); standard_only_visit_mut!(visit_mut_ts_type, TsType); standard_only_visit_mut!(visit_mut_ts_type_alias_decl, TsTypeAliasDecl); standard_only_visit_mut!(visit_mut_ts_type_ann, TsTypeAnn); standard_only_visit_mut!(visit_mut_ts_type_element, TsTypeElement); standard_only_visit_mut!(visit_mut_ts_type_lit, TsTypeLit); standard_only_visit_mut!(visit_mut_ts_type_operator, TsTypeOperator); standard_only_visit_mut!(visit_mut_ts_type_operator_op, TsTypeOperatorOp); standard_only_visit_mut!(visit_mut_ts_type_param, TsTypeParam); standard_only_visit_mut!(visit_mut_ts_type_param_decl, TsTypeParamDecl); standard_only_visit_mut!( visit_mut_ts_type_param_instantiation, TsTypeParamInstantiation ); standard_only_visit_mut!(visit_mut_ts_type_predicate, TsTypePredicate); standard_only_visit_mut!(visit_mut_ts_type_query, TsTypeQuery); standard_only_visit_mut!(visit_mut_ts_type_query_expr, TsTypeQueryExpr); standard_only_visit_mut!(visit_mut_ts_type_ref, TsTypeRef); standard_only_visit_mut!( visit_mut_ts_union_or_intersection_type, TsUnionOrIntersectionType ); standard_only_visit_mut!(visit_mut_ts_union_type, TsUnionType); standard_only_visit_mut!(visit_mut_jsx_element, JSXElement); standard_only_visit_mut!(visit_mut_jsx_fragment, JSXFragment); standard_only_visit_mut!(visit_mut_jsx_empty_expr, JSXEmptyExpr); standard_only_visit_mut!(visit_mut_jsx_member_expr, JSXMemberExpr); standard_only_visit_mut!(visit_mut_jsx_namespaced_name, JSXNamespacedName); }; } /// Note: Ignoring more types is not considered as a breaking change. #[macro_export] macro_rules! noop_visit_mut_type { (fail) => { noop_visit_mut_type!(visit_mut_accessibility, Accessibility, fail); noop_visit_mut_type!(visit_mut_true_plus_minus, TruePlusMinus, fail); noop_visit_mut_type!(visit_mut_ts_array_type, TsArrayType, fail); noop_visit_mut_type!(visit_mut_ts_call_signature_decl, TsCallSignatureDecl, fail); noop_visit_mut_type!(visit_mut_ts_conditional_type, TsConditionalType, fail); noop_visit_mut_type!( visit_mut_ts_construct_signature_decl, TsConstructSignatureDecl, fail ); noop_visit_mut_type!(visit_mut_ts_constructor_type, TsConstructorType, fail); noop_visit_mut_type!(visit_mut_ts_entity_name, TsEntityName, fail); noop_visit_mut_type!(visit_mut_ts_expr_with_type_args, TsExprWithTypeArgs, fail); noop_visit_mut_type!( visit_mut_ts_fn_or_constructor_type, TsFnOrConstructorType, fail ); noop_visit_mut_type!(visit_mut_ts_fn_param, TsFnParam, fail); noop_visit_mut_type!(visit_mut_ts_fn_type, TsFnType, fail); noop_visit_mut_type!(visit_mut_ts_import_type, TsImportType, fail); noop_visit_mut_type!(visit_mut_ts_index_signature, TsIndexSignature, fail); noop_visit_mut_type!(visit_mut_ts_indexed_access_type, TsIndexedAccessType, fail); noop_visit_mut_type!(visit_mut_ts_infer_type, TsInferType, fail); noop_visit_mut_type!(visit_mut_ts_interface_body, TsInterfaceBody, fail); noop_visit_mut_type!(visit_mut_ts_interface_decl, TsInterfaceDecl, fail); noop_visit_mut_type!(visit_mut_ts_intersection_type, TsIntersectionType, fail); noop_visit_mut_type!(visit_mut_ts_keyword_type, TsKeywordType, fail); noop_visit_mut_type!(visit_mut_ts_keyword_type_kind, TsKeywordTypeKind, fail); noop_visit_mut_type!(visit_mut_ts_mapped_type, TsMappedType, fail); noop_visit_mut_type!(visit_mut_ts_method_signature, TsMethodSignature, fail); noop_visit_mut_type!(visit_mut_ts_optional_type, TsOptionalType, fail); noop_visit_mut_type!(visit_mut_ts_parenthesized_type, TsParenthesizedType, fail); noop_visit_mut_type!(visit_mut_ts_property_signature, TsPropertySignature, fail); noop_visit_mut_type!(visit_mut_ts_qualified_name, TsQualifiedName, fail); noop_visit_mut_type!(visit_mut_ts_rest_type, TsRestType, fail); noop_visit_mut_type!(visit_mut_ts_this_type, TsThisType, fail); noop_visit_mut_type!(visit_mut_ts_this_type_or_ident, TsThisTypeOrIdent, fail); noop_visit_mut_type!(visit_mut_ts_tuple_type, TsTupleType, fail); noop_visit_mut_type!(visit_mut_ts_type, TsType, fail); noop_visit_mut_type!(visit_mut_ts_type_alias_decl, TsTypeAliasDecl, fail); noop_visit_mut_type!(visit_mut_ts_type_ann, TsTypeAnn, fail); noop_visit_mut_type!(visit_mut_ts_type_element, TsTypeElement, fail); noop_visit_mut_type!(visit_mut_ts_type_lit, TsTypeLit, fail); noop_visit_mut_type!(visit_mut_ts_type_operator, TsTypeOperator, fail); noop_visit_mut_type!(visit_mut_ts_type_operator_op, TsTypeOperatorOp, fail); noop_visit_mut_type!(visit_mut_ts_type_param, TsTypeParam, fail); noop_visit_mut_type!(visit_mut_ts_type_param_decl, TsTypeParamDecl, fail); noop_visit_mut_type!( visit_mut_ts_type_param_instantiation, TsTypeParamInstantiation, fail ); noop_visit_mut_type!(visit_mut_ts_type_predicate, TsTypePredicate, fail); noop_visit_mut_type!(visit_mut_ts_type_query, TsTypeQuery, fail); noop_visit_mut_type!(visit_mut_ts_type_query_expr, TsTypeQueryExpr, fail); noop_visit_mut_type!(visit_mut_ts_type_ref, TsTypeRef, fail); noop_visit_mut_type!( visit_mut_ts_union_or_intersection_type, TsUnionOrIntersectionType, fail ); noop_visit_mut_type!(visit_mut_ts_union_type, TsUnionType, fail); }; () => { noop_visit_mut_type!(visit_mut_accessibility, Accessibility); noop_visit_mut_type!(visit_mut_true_plus_minus, TruePlusMinus); noop_visit_mut_type!(visit_mut_ts_array_type, TsArrayType); noop_visit_mut_type!(visit_mut_ts_call_signature_decl, TsCallSignatureDecl); noop_visit_mut_type!(visit_mut_ts_conditional_type, TsConditionalType); noop_visit_mut_type!( visit_mut_ts_construct_signature_decl, TsConstructSignatureDecl ); noop_visit_mut_type!(visit_mut_ts_constructor_type, TsConstructorType); noop_visit_mut_type!(visit_mut_ts_entity_name, TsEntityName); noop_visit_mut_type!(visit_mut_ts_expr_with_type_args, TsExprWithTypeArgs); noop_visit_mut_type!(visit_mut_ts_fn_or_constructor_type, TsFnOrConstructorType); noop_visit_mut_type!(visit_mut_ts_fn_param, TsFnParam); noop_visit_mut_type!(visit_mut_ts_fn_type, TsFnType); noop_visit_mut_type!(visit_mut_ts_import_type, TsImportType); noop_visit_mut_type!(visit_mut_ts_index_signature, TsIndexSignature); noop_visit_mut_type!(visit_mut_ts_indexed_access_type, TsIndexedAccessType); noop_visit_mut_type!(visit_mut_ts_infer_type, TsInferType); noop_visit_mut_type!(visit_mut_ts_interface_body, TsInterfaceBody); noop_visit_mut_type!(visit_mut_ts_interface_decl, TsInterfaceDecl); noop_visit_mut_type!(visit_mut_ts_intersection_type, TsIntersectionType); noop_visit_mut_type!(visit_mut_ts_keyword_type, TsKeywordType); noop_visit_mut_type!(visit_mut_ts_keyword_type_kind, TsKeywordTypeKind); noop_visit_mut_type!(visit_mut_ts_mapped_type, TsMappedType); noop_visit_mut_type!(visit_mut_ts_method_signature, TsMethodSignature); noop_visit_mut_type!(visit_mut_ts_optional_type, TsOptionalType); noop_visit_mut_type!(visit_mut_ts_parenthesized_type, TsParenthesizedType); noop_visit_mut_type!(visit_mut_ts_property_signature, TsPropertySignature); noop_visit_mut_type!(visit_mut_ts_qualified_name, TsQualifiedName); noop_visit_mut_type!(visit_mut_ts_rest_type, TsRestType); noop_visit_mut_type!(visit_mut_ts_this_type, TsThisType); noop_visit_mut_type!(visit_mut_ts_this_type_or_ident, TsThisTypeOrIdent); noop_visit_mut_type!(visit_mut_ts_tuple_type, TsTupleType); noop_visit_mut_type!(visit_mut_ts_type, TsType); noop_visit_mut_type!(visit_mut_ts_type_alias_decl, TsTypeAliasDecl); noop_visit_mut_type!(visit_mut_ts_type_ann, TsTypeAnn); noop_visit_mut_type!(visit_mut_ts_type_element, TsTypeElement); noop_visit_mut_type!(visit_mut_ts_type_lit, TsTypeLit); noop_visit_mut_type!(visit_mut_ts_type_operator, TsTypeOperator); noop_visit_mut_type!(visit_mut_ts_type_operator_op, TsTypeOperatorOp); noop_visit_mut_type!(visit_mut_ts_type_param, TsTypeParam); noop_visit_mut_type!(visit_mut_ts_type_param_decl, TsTypeParamDecl); noop_visit_mut_type!( visit_mut_ts_type_param_instantiation, TsTypeParamInstantiation ); noop_visit_mut_type!(visit_mut_ts_type_predicate, TsTypePredicate); noop_visit_mut_type!(visit_mut_ts_type_query, TsTypeQuery); noop_visit_mut_type!(visit_mut_ts_type_query_expr, TsTypeQueryExpr); noop_visit_mut_type!(visit_mut_ts_type_ref, TsTypeRef); noop_visit_mut_type!( visit_mut_ts_union_or_intersection_type, TsUnionOrIntersectionType ); noop_visit_mut_type!(visit_mut_ts_union_type, TsUnionType); }; ($name:ident, $N:ident, fail) => { #[cfg_attr(not(debug_assertions), inline(always))] fn $name(&mut self, _: &mut $crate::swc_ecma_ast::$N) { $crate::fail_no_typescript(stringify!($name)); } }; ($name:ident, $N:ident) => { fn $name(&mut self, _: &mut $crate::swc_ecma_ast::$N) {} }; } #[macro_export] macro_rules! visit_obj_and_computed { () => { fn visit_member_prop(&mut self, n: &$crate::swc_ecma_ast::MemberProp) { if let $crate::swc_ecma_ast::MemberProp::Computed(c) = n { c.visit_with(self); } } fn visit_jsx_member_expr(&mut self, n: &$crate::swc_ecma_ast::JSXMemberExpr) { n.obj.visit_with(self); } fn visit_super_prop(&mut self, n: &$crate::swc_ecma_ast::SuperProp) { if let $crate::swc_ecma_ast::SuperProp::Computed(c) = n { c.visit_with(self); } } }; } #[macro_export] macro_rules! visit_mut_obj_and_computed { () => { fn visit_mut_member_prop(&mut self, n: &mut $crate::swc_ecma_ast::MemberProp) { if let $crate::swc_ecma_ast::MemberProp::Computed(c) = n { c.visit_mut_with(self); } } fn visit_mut_jsx_member_expr(&mut self, n: &mut $crate::swc_ecma_ast::JSXMemberExpr) { n.obj.visit_mut_with(self); } fn visit_mut_super_prop(&mut self, n: &mut $crate::swc_ecma_ast::SuperProp) { if let $crate::swc_ecma_ast::SuperProp::Computed(c) = n { c.visit_mut_with(self); } } }; } macro_rules! impl_traits_for_tuple { ( [$idx:tt, $name:ident], $([$idx_rest:tt, $name_rest:ident]),* ) => { impl<$name, $($name_rest),*> VisitMut for ($name, $($name_rest),*) where $name: VisitMut, $($name_rest: VisitMut),* { fn visit_mut_program(&mut self, program: &mut Program) { self.$idx.visit_mut_program(program); $( self.$idx_rest.visit_mut_program(program); )* } fn visit_mut_module(&mut self, module: &mut Module) { self.$idx.visit_mut_module(module); $( self.$idx_rest.visit_mut_module(module); )* } fn visit_mut_script(&mut self, script: &mut Script) { self.$idx.visit_mut_script(script); $( self.$idx_rest.visit_mut_script(script); )* } fn visit_mut_stmt(&mut self, stmt: &mut Stmt) { self.$idx.visit_mut_stmt(stmt); $( self.$idx_rest.visit_mut_stmt(stmt); )* } fn visit_mut_expr(&mut self, expr: &mut Expr) { self.$idx.visit_mut_expr(expr); $( self.$idx_rest.visit_mut_expr(expr); )* } fn visit_mut_pat(&mut self, pat: &mut Pat) { self.$idx.visit_mut_pat(pat); $( self.$idx_rest.visit_mut_pat(pat); )* } fn visit_mut_assign_target(&mut self, target: &mut AssignTarget) { self.$idx.visit_mut_assign_target(target); $( self.$idx_rest.visit_mut_assign_target(target); )* } fn visit_mut_ident(&mut self, ident: &mut Ident) { self.$idx.visit_mut_ident(ident); $( self.$idx_rest.visit_mut_ident(ident); )* } } }; } impl_traits_for_tuple!([0, A], [1, B]); impl_traits_for_tuple!([0, A], [1, B], [2, C]); impl_traits_for_tuple!([0, A], [1, B], [2, C], [3, D]); impl_traits_for_tuple!([0, A], [1, B], [2, C], [3, D], [4, E]); impl_traits_for_tuple!([0, A], [1, B], [2, C], [3, D], [4, E], [5, F]); impl_traits_for_tuple!([0, A], [1, B], [2, C], [3, D], [4, E], [5, F], [6, G]); impl_traits_for_tuple!( [0, A], [1, B], [2, C], [3, D], [4, E], [5, F], [6, G], [7, H] ); impl_traits_for_tuple!( [0, A], [1, B], [2, C], [3, D], [4, E], [5, F], [6, G], [7, H], [8, I] ); impl_traits_for_tuple!( [0, A], [1, B], [2, C], [3, D], [4, E], [5, F], [6, G], [7, H], [8, I], [9, J] ); impl_traits_for_tuple!( [0, A], [1, B], [2, C], [3, D], [4, E], [5, F], [6, G], [7, H], [8, I], [9, J], [10, K] ); impl_traits_for_tuple!( [0, A], [1, B], [2, C], [3, D], [4, E], [5, F], [6, G], [7, H], [8, I], [9, J], [10, K], [11, L] ); impl_traits_for_tuple!( [0, A], [1, B], [2, C], [3, D], [4, E], [5, F], [6, G], [7, H], [8, I], [9, J], [10, K], [11, L], [12, M] );
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_visit/tests/main.rs
Rust
use swc_common::DUMMY_SP; use swc_ecma_ast::*; use swc_ecma_visit::NodeRef; #[test] fn traverse_lookup() { let node = Expr::Call(CallExpr { span: DUMMY_SP, callee: Callee::Expr( AwaitExpr { span: DUMMY_SP, arg: Ident::new_no_ctxt("foo".into(), DUMMY_SP).into(), } .into(), ), args: Vec::new(), ..Default::default() }); let node_ref = NodeRef::from(&node); let iter = node_ref.experimental_traverse(); let mut has_await = false; for node in iter { has_await |= matches!(node, NodeRef::AwaitExpr(..)); } assert!(has_await); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecma_visit_std/src/lib.rs
Rust
#![cfg_attr(docsrs, feature(doc_cfg))] #[doc(hidden)] pub extern crate swc_ecma_ast; pub use self::generated::*; mod generated;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_ecmascript/src/lib.rs
Rust
#![deny(clippy::all)] #![cfg_attr(docsrs, feature(doc_cfg))] pub use swc_ecma_ast as ast; #[cfg(feature = "codegen")] #[cfg_attr(docsrs, doc(cfg(feature = "codegen")))] pub use swc_ecma_codegen as codegen; #[cfg(feature = "minifier")] #[cfg_attr(docsrs, doc(cfg(feature = "minifier")))] pub use swc_ecma_minifier as minifier; #[cfg(feature = "parser")] #[cfg_attr(docsrs, doc(cfg(feature = "parser")))] pub use swc_ecma_parser as parser; #[cfg(feature = "preset_env")] #[cfg_attr(docsrs, doc(cfg(feature = "preset_env")))] pub use swc_ecma_preset_env as preset_env; #[cfg(feature = "swc_ecma_quote")] #[cfg_attr(docsrs, doc(cfg(feature = "parser")))] pub use swc_ecma_quote as quote; #[cfg(feature = "transforms")] #[cfg_attr(docsrs, doc(cfg(feature = "transforms")))] pub use swc_ecma_transforms as transforms; #[cfg(feature = "utils")] #[cfg_attr(docsrs, doc(cfg(feature = "utils")))] pub use swc_ecma_utils as utils; #[cfg(feature = "visit")] #[cfg_attr(docsrs, doc(cfg(feature = "visit")))] pub use swc_ecma_visit as visit;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_eq_ignore_macros/src/lib.rs
Rust
use proc_macro2::Span; use quote::quote; use syn::{ parse, parse_quote, punctuated::Punctuated, spanned::Spanned, Arm, BinOp, Block, Data, DeriveInput, Expr, ExprBinary, ExprBlock, Field, FieldPat, Fields, Ident, Index, Member, Pat, PatIdent, PatRest, PatStruct, PatTuple, Path, Stmt, Token, }; /// Derives `swc_common::TypeEq`. /// /// - Field annotated with `#[use_eq]` will be compared using `==`. /// - Field annotated with `#[not_type]` will be ignored #[proc_macro_derive(TypeEq, attributes(not_type, use_eq, use_eq_ignore_span))] pub fn derive_type_eq(item: proc_macro::TokenStream) -> proc_macro::TokenStream { Deriver { trait_name: Ident::new("TypeEq", Span::call_site()), method_name: Ident::new("type_eq", Span::call_site()), ignore_field: Box::new(|field| { // Search for `#[not_type]`. for attr in &field.attrs { if attr.path().is_ident("not_type") { return true; } } false }), } .derive(item) } /// Derives `swc_common::EqIgnoreSpan`. /// /// /// Fields annotated with `#[not_spanned]` or `#[use_eq]` will use` ==` instead /// of `eq_ignore_span`. #[proc_macro_derive(EqIgnoreSpan, attributes(not_spanned, use_eq))] pub fn derive_eq_ignore_span(item: proc_macro::TokenStream) -> proc_macro::TokenStream { Deriver { trait_name: Ident::new("EqIgnoreSpan", Span::call_site()), method_name: Ident::new("eq_ignore_span", Span::call_site()), ignore_field: Box::new(|_field| { // We call eq_ignore_span for all fields. false }), } .derive(item) } struct Deriver { trait_name: Ident, method_name: Ident, ignore_field: Box<dyn Fn(&Field) -> bool>, } impl Deriver { fn derive(&self, item: proc_macro::TokenStream) -> proc_macro::TokenStream { let input: DeriveInput = parse(item).unwrap(); let body = self.make_body(&input.data); let trait_name = &self.trait_name; let ty = &input.ident; let method_name = &self.method_name; quote!( #[automatically_derived] impl ::swc_common::#trait_name for #ty { #[allow(non_snake_case)] fn #method_name(&self, other: &Self) -> bool { #body } } ) .into() } fn make_body(&self, data: &Data) -> Expr { match data { Data::Struct(s) => { let arm = self.make_arm_from_fields(parse_quote!(Self), &s.fields); parse_quote!(match (self, other) { #arm }) } Data::Enum(e) => { // let mut arms = Punctuated::<_, Token![,]>::default(); for v in &e.variants { let vi = &v.ident; let arm = self.make_arm_from_fields(parse_quote!(Self::#vi), &v.fields); arms.push(arm); } arms.push(parse_quote!(_ => false)); parse_quote!(match (self, other) { #arms }) } Data::Union(_) => unimplemented!("union"), } } fn make_arm_from_fields(&self, pat_path: Path, fields: &Fields) -> Arm { let mut l_pat_fields = Punctuated::<_, Token![,]>::default(); let mut r_pat_fields = Punctuated::<_, Token![,]>::default(); let mut exprs = Vec::new(); for (i, field) in fields .iter() .enumerate() .filter(|(_, f)| !(self.ignore_field)(f)) { let method_name = if field.attrs.iter().any(|attr| { attr.path().is_ident("not_spanned") || attr.path().is_ident("use_eq") }) { Ident::new("eq", Span::call_site()) } else if field .attrs .iter() .any(|attr| attr.path().is_ident("use_eq_ignore_span")) { Ident::new("eq_ignore_span", Span::call_site()) } else { self.method_name.clone() }; let base = field .ident .clone() .unwrap_or_else(|| Ident::new(&format!("_{}", i), field.ty.span())); // let l_binding_ident = Ident::new(&format!("_l_{}", base), base.span()); let r_binding_ident = Ident::new(&format!("_r_{}", base), base.span()); let make_pat_field = |ident: &Ident| FieldPat { attrs: Default::default(), member: match &field.ident { Some(v) => Member::Named(v.clone()), None => Member::Unnamed(Index { index: i as _, span: field.ty.span(), }), }, colon_token: Some(Token![:](ident.span())), pat: Box::new(Pat::Ident(PatIdent { attrs: Default::default(), by_ref: Some(Token![ref](ident.span())), mutability: None, ident: ident.clone(), subpat: None, })), }; l_pat_fields.push(make_pat_field(&l_binding_ident)); r_pat_fields.push(make_pat_field(&r_binding_ident)); exprs.push(parse_quote!(#l_binding_ident.#method_name(#r_binding_ident))); } // true && a.type_eq(&other.a) && b.type_eq(&other.b) let mut expr: Expr = parse_quote!(true); for expr_el in exprs { expr = Expr::Binary(ExprBinary { attrs: Default::default(), left: Box::new(expr), op: BinOp::And(Token![&&](Span::call_site())), right: Box::new(expr_el), }); } Arm { attrs: Default::default(), pat: Pat::Tuple(PatTuple { attrs: Default::default(), paren_token: Default::default(), elems: { let mut elems = Punctuated::default(); elems.push(Pat::Struct(PatStruct { attrs: Default::default(), qself: None, path: pat_path.clone(), brace_token: Default::default(), fields: l_pat_fields, rest: Some(PatRest { attrs: Default::default(), dot2_token: Token![..](Span::call_site()), }), })); elems.push(Pat::Struct(PatStruct { attrs: Default::default(), qself: None, path: pat_path, brace_token: Default::default(), fields: r_pat_fields, rest: Some(PatRest { attrs: Default::default(), dot2_token: Token![..](Span::call_site()), }), })); elems }, }), guard: Default::default(), fat_arrow_token: Token![=>](Span::call_site()), body: Box::new(Expr::Block(ExprBlock { attrs: Default::default(), label: Default::default(), block: Block { brace_token: Default::default(), stmts: vec![Stmt::Expr(expr, None)], }, })), comma: Default::default(), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_error_reporters/examples/swc_try.rs
Rust
//! This is actual code used by swc. use std::{ fmt, sync::{Arc, Mutex}, }; use swc_common::{errors::Handler, sync::Lrc, BytePos, FileName, SourceFile, SourceMap, Span}; use swc_error_reporters::{GraphicalReportHandler, PrettyEmitter, PrettyEmitterConfig}; fn main() { let cm = Lrc::<SourceMap>::default(); let wr = Box::<LockedWriter>::default(); let emitter = PrettyEmitter::new( cm.clone(), wr.clone(), GraphicalReportHandler::new().with_context_lines(3), PrettyEmitterConfig { skip_filename: false, }, ); // let e_wr = EmitterWriter::new(wr.clone(), Some(cm), false, // true).skip_filename(skip_filename); let handler = Handler::with_emitter(true, false, Box::new(emitter)); let fm1 = cm.new_source_file( Lrc::new(FileName::Custom("foo.js".into())), "13579\n12345\n13579".into(), ); let fm2 = cm.new_source_file( Lrc::new(FileName::Custom("bar.js".into())), "02468\n12345\n02468".into(), ); // This is a simple example. handler .struct_span_err(span(&fm1, 0, 3), "simple message") .emit(); // We can show other file. // This can be used to show configurable error with the config. handler .struct_span_err(span(&fm1, 6, 9), "constraint violation") .span_note(span(&fm2, 0, 1), "this is your config") .emit(); let s = &**wr.0.lock().unwrap(); println!("{}", s); } /// Don't do this in your real app. You should use [Span] created by parser fn span(base: &SourceFile, lo: u32, hi: u32) -> Span { let lo = base.start_pos.0 + lo; let hi = base.start_pos.0 + hi; Span::new(BytePos(lo), BytePos(hi)) } #[derive(Clone, Default)] struct LockedWriter(Arc<Mutex<String>>); impl fmt::Write for LockedWriter { fn write_str(&mut self, s: &str) -> fmt::Result { self.0.lock().unwrap().push_str(s); Ok(()) } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_error_reporters/src/handler.rs
Rust
use std::{env, fmt, io::Write, mem::take, sync::Arc}; use anyhow::Error; use miette::{GraphicalReportHandler, GraphicalTheme}; use once_cell::sync::Lazy; use parking_lot::Mutex; use swc_common::{ errors::{ColorConfig, Emitter, Handler, HANDLER}, sync::Lrc, SourceMap, }; use crate::{ json_emitter::{JsonEmitter, JsonEmitterConfig}, PrettyEmitter, PrettyEmitterConfig, }; #[derive(Clone, Default)] struct LockedWriter(Arc<Mutex<Vec<u8>>>); impl Write for LockedWriter { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { let mut lock = self.0.lock(); lock.extend_from_slice(buf); Ok(buf.len()) } fn flush(&mut self) -> std::io::Result<()> { Ok(()) } } impl fmt::Write for LockedWriter { fn write_str(&mut self, s: &str) -> fmt::Result { self.write(s.as_bytes()).map_err(|_| fmt::Error)?; Ok(()) } } #[derive(Debug, Clone)] pub struct HandlerOpts { /// [ColorConfig::Auto] is the default, and it will print colors unless the /// environment variable `NO_COLOR` is not 1. pub color: ColorConfig, /// Defaults to `false`. pub skip_filename: bool, } impl Default for HandlerOpts { fn default() -> Self { Self { color: ColorConfig::Auto, skip_filename: false, } } } fn to_miette_reporter(color: ColorConfig) -> GraphicalReportHandler { match color { ColorConfig::Auto => { if cfg!(target_arch = "wasm32") { return to_miette_reporter(ColorConfig::Always).with_context_lines(3); } static ENABLE: Lazy<bool> = Lazy::new(|| !env::var("NO_COLOR").map(|s| s == "1").unwrap_or(false)); if *ENABLE { to_miette_reporter(ColorConfig::Always) } else { to_miette_reporter(ColorConfig::Never) } } ColorConfig::Always => GraphicalReportHandler::default(), ColorConfig::Never => GraphicalReportHandler::default().with_theme(GraphicalTheme::none()), } .with_context_lines(3) } /// Try operation with a [Handler] and prints the errors as a [String] wrapped /// by [Err]. pub fn try_with_handler<F, Ret>( cm: Lrc<SourceMap>, config: HandlerOpts, op: F, ) -> Result<Ret, Error> where F: FnOnce(&Handler) -> Result<Ret, Error>, { try_with_handler_inner(cm, config, op, false) } /// Try operation with a [Handler] and prints the errors as a [String] wrapped /// by [Err]. pub fn try_with_json_handler<F, Ret>( cm: Lrc<SourceMap>, config: HandlerOpts, op: F, ) -> Result<Ret, Error> where F: FnOnce(&Handler) -> Result<Ret, Error>, { try_with_handler_inner(cm, config, op, true) } fn try_with_handler_inner<F, Ret>( cm: Lrc<SourceMap>, config: HandlerOpts, op: F, json: bool, ) -> Result<Ret, Error> where F: FnOnce(&Handler) -> Result<Ret, Error>, { let wr = Box::<LockedWriter>::default(); let emitter: Box<dyn Emitter> = if json { Box::new(JsonEmitter::new( cm, wr.clone(), JsonEmitterConfig { skip_filename: config.skip_filename, }, )) } else { Box::new(PrettyEmitter::new( cm, wr.clone(), to_miette_reporter(config.color), PrettyEmitterConfig { skip_filename: config.skip_filename, }, )) }; // let e_wr = EmitterWriter::new(wr.clone(), Some(cm), false, // true).skip_filename(skip_filename); let handler = Handler::with_emitter(true, false, emitter); let ret = HANDLER.set(&handler, || op(&handler)); if handler.has_errors() { let mut lock = wr.0.lock(); let error = take(&mut *lock); let msg = String::from_utf8(error).expect("error string should be utf8"); match ret { Ok(_) => Err(anyhow::anyhow!(msg)), Err(err) => Err(err.context(msg)), } } else { ret } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_error_reporters/src/json_emitter.rs
Rust
use std::fmt::Write; use serde_derive::Serialize; use swc_common::{ errors::{DiagnosticBuilder, DiagnosticId, Emitter}, sync::Lrc, SourceMap, SourceMapper, }; use crate::WriterWrapper; pub struct JsonEmitter { cm: Lrc<SourceMap>, wr: WriterWrapper, config: JsonEmitterConfig, diagnostics: Vec<String>, } impl JsonEmitter { pub fn new( cm: Lrc<SourceMap>, wr: Box<dyn Write + Send + Sync>, config: JsonEmitterConfig, ) -> Self { Self { cm, wr: WriterWrapper(wr), config, diagnostics: vec![], } } } #[derive(Debug, Clone, Default)] pub struct JsonEmitterConfig { pub skip_filename: bool, } impl Emitter for JsonEmitter { fn emit(&mut self, db: &DiagnosticBuilder) { let d = &**db; let children = d .children .iter() .map(|d| todo!("json subdiagnostic: {d:?}")) .collect::<Vec<_>>(); let error_code = match &d.code { Some(DiagnosticId::Error(s)) => Some(&**s), Some(DiagnosticId::Lint(s)) => Some(&**s), None => None, }; let loc = d .span .primary_span() .and_then(|span| self.cm.try_lookup_char_pos(span.lo()).ok()); let snippet = d .span .primary_span() .and_then(|span| self.cm.span_to_snippet(span).ok()); let filename = if self.config.skip_filename { None } else { loc.as_ref().map(|loc| loc.file.name.to_string()) }; let error = JsonDiagnostic { code: error_code, message: &d.message[0].0, snippet: snippet.as_deref(), filename: filename.as_deref(), line: loc.as_ref().map(|loc| loc.line), column: loc.as_ref().map(|loc| loc.col_display), children, }; let result = serde_json::to_string(&error).unwrap(); self.wr.write_str(&result).unwrap(); writeln!(self.wr).unwrap(); self.diagnostics.push(result); } fn take_diagnostics(&mut self) -> Vec<String> { std::mem::take(&mut self.diagnostics) } } #[derive(Serialize)] struct JsonDiagnostic<'a> { /// Error code #[serde(skip_serializing_if = "Option::is_none")] code: Option<&'a str>, message: &'a str, #[serde(skip_serializing_if = "Option::is_none")] snippet: Option<&'a str>, #[serde(skip_serializing_if = "Option::is_none")] filename: Option<&'a str>, #[serde(skip_serializing_if = "Option::is_none")] line: Option<usize>, #[serde(skip_serializing_if = "Option::is_none")] column: Option<usize>, #[serde(skip_serializing_if = "Vec::is_empty")] children: Vec<JsonSubdiagnostic<'a>>, } #[derive(Serialize)] struct JsonSubdiagnostic<'a> { message: &'a str, snippet: Option<&'a str>, filename: &'a str, line: usize, }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_error_reporters/src/lib.rs
Rust
use std::{ fmt::{self, Write}, intrinsics::transmute, }; pub use miette::{GraphicalReportHandler, GraphicalTheme}; use miette::{ LabeledSpan, MietteError, Severity, SourceCode, SourceOffset, SourceSpan, SpanContents, }; use swc_common::{ errors::{DiagnosticBuilder, DiagnosticId, Emitter, Level, SubDiagnostic}, sync::Lrc, BytePos, FileName, SourceMap, Span, }; pub mod handler; pub mod json_emitter; pub struct PrettyEmitter { cm: Lrc<SourceMap>, wr: WriterWrapper, reporter: GraphicalReportHandler, config: PrettyEmitterConfig, diagnostics: Vec<String>, } #[derive(Debug, Clone, Default)] pub struct PrettyEmitterConfig { pub skip_filename: bool, } impl PrettyEmitter { pub fn new( cm: Lrc<SourceMap>, wr: Box<dyn Write + Send + Sync>, reporter: GraphicalReportHandler, config: PrettyEmitterConfig, ) -> Self { Self { cm, wr: WriterWrapper(wr), reporter, config, diagnostics: vec![], } } } struct WriterWrapper(Box<dyn Write + Send + Sync>); impl Write for WriterWrapper { fn write_str(&mut self, s: &str) -> fmt::Result { self.0.write_str(s) } fn write_char(&mut self, c: char) -> fmt::Result { self.0.write_char(c) } fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result { self.0.write_fmt(args) } } #[derive(Clone, Copy)] struct MietteSourceCode<'a> { cm: &'a SourceMap, skip_filename: bool, } impl SourceCode for MietteSourceCode<'_> { fn read_span<'a>( &'a self, span: &SourceSpan, context_lines_before: usize, context_lines_after: usize, ) -> Result<Box<dyn SpanContents<'a> + 'a>, MietteError> { let lo = span.offset(); let hi = lo + span.len(); let mut span = Span::new(BytePos(lo as _), BytePos(hi as _)); span = self .cm .with_span_to_prev_source(span, |src| { let len = src .rsplit('\n') .take(context_lines_before + 1) .map(|s| s.len() + 1) .sum::<usize>(); span.lo.0 -= (len as u32) - 1; span }) .unwrap_or(span); span = self .cm .with_span_to_next_source(span, |src| { let len = src .split('\n') .take(context_lines_after + 1) .map(|s| s.len() + 1) .sum::<usize>(); span.hi.0 += (len as u32) - 1; span }) .unwrap_or(span); span = self .cm .with_snippet_of_span(span, |src| { if src.lines().next().is_some() { return span; } let lo = src.len() - src.trim_start().len(); let hi = src.len() - src.trim_end().len(); span.lo.0 += lo as u32; span.hi.0 -= hi as u32; span }) .unwrap_or(span); let mut src = self .cm .with_snippet_of_span(span, |s| unsafe { transmute::<&str, &str>(s) }) .unwrap_or(" "); if span.lo == span.hi { src = " "; } let loc = self.cm.lookup_char_pos(span.lo()); let line_count = loc.file.analyze().lines.len(); let name = if self.skip_filename { None } else { match &*loc.file.name { FileName::Real(ref path) => Some(path.to_string_lossy().into_owned()), FileName::Custom(ref name) => Some(name.clone()), FileName::Anon => None, _ => Some(loc.file.name.to_string()), } }; Ok(Box::new(SpanContentsImpl { _cm: self.cm, data: src, span: convert_span(span), line: loc.line.saturating_sub(1), column: loc.col_display, line_count, name, })) } } impl Emitter for PrettyEmitter { fn emit(&mut self, db: &DiagnosticBuilder) { let d = &**db; let source_code = MietteSourceCode { cm: &self.cm, skip_filename: self.config.skip_filename, }; let children = d .children .iter() .filter(|d| !matches!(d.level, Level::Help)) .map(|d| MietteSubdiagnostic { source_code, d }) .collect::<Vec<_>>(); let diagnostic = MietteDiagnostic { source_code, d, children, }; let mut format_result = String::new(); self.reporter .render_report(&mut format_result, &diagnostic) .unwrap(); self.wr.write_str(&format_result).unwrap(); self.diagnostics.push(format_result); } fn take_diagnostics(&mut self) -> Vec<String> { std::mem::take(&mut self.diagnostics) } } struct MietteDiagnostic<'a> { source_code: MietteSourceCode<'a>, d: &'a swc_common::errors::Diagnostic, children: Vec<MietteSubdiagnostic<'a>>, } impl miette::Diagnostic for MietteDiagnostic<'_> { fn code<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> { self.d .code .as_ref() .map(|v| match v { DiagnosticId::Error(v) => v, DiagnosticId::Lint(v) => v, }) .map(|code| Box::new(code) as Box<dyn fmt::Display>) } fn severity(&self) -> Option<Severity> { level_to_severity(self.d.level) } fn help<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> { self.d .children .iter() .filter(|s| s.level == Level::Help) .map(|s| Box::new(&s.message[0].0) as Box<_>) .next() } fn url<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> { None } fn source_code(&self) -> Option<&dyn SourceCode> { // empty file if let Some(span) = self.d.span.primary_span() { if span.lo.is_dummy() || span.hi.is_dummy() { return None; } } else { return None; } Some(&self.source_code as &dyn SourceCode) } fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> { let iter = self.d.span.span_labels().into_iter().map(|span_label| { LabeledSpan::new_with_span(span_label.label, convert_span(span_label.span)) }); Some(Box::new(iter)) } fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn miette::Diagnostic> + 'a>> { if self.children.is_empty() { None } else { Some(Box::new( self.children.iter().map(|d| d as &dyn miette::Diagnostic), )) } } } impl std::error::Error for MietteDiagnostic<'_> {} /// Delegates to `Diagnostics` impl fmt::Debug for MietteDiagnostic<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.d, f) } } impl fmt::Display for MietteDiagnostic<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.d.message[0].0, f) } } fn convert_span(span: Span) -> SourceSpan { let len = span.hi - span.lo; let start = SourceOffset::from(span.lo.0 as usize); SourceSpan::new(start, len.0 as usize) } struct MietteSubdiagnostic<'a> { source_code: MietteSourceCode<'a>, d: &'a SubDiagnostic, } impl miette::Diagnostic for MietteSubdiagnostic<'_> { fn code<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> { None } fn severity(&self) -> Option<Severity> { level_to_severity(self.d.level) } fn help<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> { None } fn url<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> { None } fn source_code(&self) -> Option<&dyn SourceCode> { Some(&self.source_code) } fn labels(&self) -> Option<Box<dyn Iterator<Item = LabeledSpan> + '_>> { let iter = self.d.span.span_labels().into_iter().map(|span_label| { LabeledSpan::new_with_span(span_label.label, convert_span(span_label.span)) }); Some(Box::new(iter)) } fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn miette::Diagnostic> + 'a>> { None } } impl std::error::Error for MietteSubdiagnostic<'_> {} /// Delegates to `Diagnostics` impl fmt::Debug for MietteSubdiagnostic<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.d, f) } } impl fmt::Display for MietteSubdiagnostic<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.d.message[0].0, f) } } struct SpanContentsImpl<'a> { /// This ensures that the underlying sourcemap is not dropped. _cm: &'a SourceMap, // Data from a [`SourceCode`], in bytes. data: &'a str, // span actually covered by this SpanContents. span: SourceSpan, // The 0-indexed line where the associated [`SourceSpan`] _starts_. line: usize, // The 0-indexed column where the associated [`SourceSpan`] _starts_. column: usize, // Number of line in this snippet. line_count: usize, // Optional filename name: Option<String>, } impl<'a> SpanContents<'a> for SpanContentsImpl<'a> { fn data(&self) -> &'a [u8] { self.data.as_bytes() } fn span(&self) -> &SourceSpan { &self.span } fn line(&self) -> usize { self.line } fn column(&self) -> usize { self.column } fn line_count(&self) -> usize { self.line_count } fn name(&self) -> Option<&str> { self.name.as_deref() } } fn level_to_severity(level: Level) -> Option<Severity> { match level { Level::FailureNote | Level::Bug | Level::Fatal | Level::PhaseFatal | Level::Error => { Some(Severity::Error) } Level::Warning => Some(Severity::Warning), Level::Note | Level::Help => Some(Severity::Advice), Level::Cancelled => None, } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_error_reporters/tests/fixture.rs
Rust
#![deny(warnings)] use std::{fmt, fmt::Write, fs, path::Path}; use swc_common::{ errors::{Handler, Level}, sync::{Lock, Lrc}, BytePos, FileName, SourceMap, Span, }; use swc_error_reporters::PrettyEmitter; #[derive(Clone, Default)] struct Writer(Lrc<Lock<String>>); impl Write for Writer { fn write_str(&mut self, s: &str) -> fmt::Result { self.0.lock().write_str(s) } } fn output<F>(file: &str, op: F) where F: FnOnce(Lrc<SourceMap>, &Handler), { let cm = Lrc::new(SourceMap::default()); let wr = Writer::default(); let emitter = PrettyEmitter::new( cm.clone(), Box::new(wr.clone()), Default::default(), Default::default(), ); let handler = Handler::with_emitter(true, false, Box::new(emitter)); op(cm, &handler); let output = Path::new("tests").join("fixture").join(file); let s = wr.0.lock().as_str().to_string(); println!("{}", s); fs::write(output, &s).expect("failed to write"); } fn span(start: usize, end: usize) -> Span { Span::new(BytePos(start as _), BytePos(end as _)) } #[test] fn test_1() { output("1.ans", |cm, h| { let _fm = cm.new_source_file(FileName::Anon.into(), "123456789".into()); h.struct_span_err(span(1, 3), "test") .span_label(span(1, 4), "label") .emit(); }); } #[test] fn test_2() { output("2.ans", |cm, h| { let _fm = cm.new_source_file(FileName::Anon.into(), "123456789".into()); let mut d = h.struct_span_err(span(1, 3), "test"); d.span_label(span(1, 4), "label") .span_help(span(1, 5), "help") // This does not work. .span_suggestion(span(2, 3), "suggesting message", "132".into()); d.sub(Level::Warning, "sub1", Some(span(7, 8))); d.sub(Level::Warning, "sub2", Some(span(6, 8))); d.emit(); }); }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_ast/src/class.rs
Rust
use serde::{ser::SerializeMap, Deserialize, Serialize}; use serde_json::Value; use swc_common::ast_serde; use crate::{ common::{ Access, BaseNode, Decorator, Identifier, Param, PrivateName, SuperTypeParams, TypeAnnotOrNoop, TypeParamDeclOrNoop, }, expr::{ClassExpression, Expression}, flavor::Flavor, flow::{ClassImplements, InterfaceExtends}, object::ObjectKey, stmt::{BlockStatement, Statement}, typescript::{TSDeclareMethod, TSExpressionWithTypeArguments, TSIndexSignature}, }; #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Class { #[tag("ClassExpression")] Expr(ClassExpression), #[tag("ClassDeclaration")] Decl(ClassDeclaration), } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum ClassMethodKind { Get, Set, Method, Constructor, } #[derive(Debug, Clone, PartialEq, Deserialize)] pub struct ClassMethod { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub kind: Option<ClassMethodKind>, pub key: ObjectKey, #[serde(default)] pub params: Vec<Param>, pub body: BlockStatement, #[serde(default)] pub computed: Option<bool>, #[serde( default, rename = "static", skip_serializing_if = "crate::flavor::Flavor::skip_none_and_false" )] pub is_static: Option<bool>, #[serde( default, skip_serializing_if = "crate::flavor::Flavor::skip_none_and_false" )] pub generator: Option<bool>, #[serde( default, rename = "async", serialize_with = "crate::ser::serialize_as_bool" )] pub is_async: Option<bool>, #[serde( default, rename = "abstract", skip_serializing_if = "crate::flavor::Flavor::skip_none" )] pub is_abstract: Option<bool>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub access: Option<Access>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub accessibility: Option<Access>, #[serde(default)] pub decorators: Option<Vec<Decorator>>, #[serde(default)] pub optional: Option<bool>, #[serde(default)] pub return_type: Option<Box<TypeAnnotOrNoop>>, #[serde(default)] pub type_parameters: Option<TypeParamDeclOrNoop>, } #[derive(Serialize)] struct BabelClassMethod<'a> { #[serde(rename = "type")] type_: &'a str, #[serde(flatten)] pub base: &'a BaseNode, #[serde(default)] pub kind: Option<ClassMethodKind>, pub key: &'a ObjectKey, #[serde(default)] pub params: &'a [Param], pub body: &'a BlockStatement, #[serde(default)] pub computed: Option<bool>, #[serde( default, rename = "static", skip_serializing_if = "crate::flavor::Flavor::skip_none_and_false" )] pub is_static: Option<bool>, #[serde( default, skip_serializing_if = "crate::flavor::Flavor::skip_none_and_false" )] pub generator: Option<bool>, #[serde( default, rename = "async", serialize_with = "crate::ser::serialize_as_bool" )] pub is_async: Option<bool>, #[serde( default, rename = "abstract", skip_serializing_if = "crate::flavor::Flavor::skip_none" )] pub is_abstract: Option<bool>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub access: Option<&'a Access>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub accessibility: Option<&'a Access>, #[serde(default)] pub decorators: Option<&'a [Decorator]>, #[serde(default)] pub optional: Option<bool>, #[serde(default)] pub return_type: Option<&'a TypeAnnotOrNoop>, #[serde(default)] pub type_parameters: Option<&'a TypeParamDeclOrNoop>, } #[derive(Serialize)] struct AcornClassMethodValue<'a> { /// `FunctionExpression` #[serde(rename = "type")] type_: &'a str, #[serde(flatten)] base: &'a BaseNode, body: &'a BlockStatement, params: &'a [Param], generator: bool, #[serde(rename = "async")] is_async: bool, } impl Serialize for ClassMethod { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { match Flavor::current() { Flavor::Babel => { let actual = BabelClassMethod { type_: "ClassMethod", base: &self.base, kind: self.kind, key: &self.key, params: &self.params, body: &self.body, computed: self.computed, is_static: self.is_static, generator: self.generator, is_async: self.is_async, is_abstract: self.is_abstract, access: self.access.as_ref(), accessibility: self.accessibility.as_ref(), decorators: self.decorators.as_deref(), optional: self.optional, return_type: self.return_type.as_deref(), type_parameters: self.type_parameters.as_ref(), }; actual.serialize(serializer) } Flavor::Acorn { .. } => { let mut s = serializer.serialize_map(None)?; { // TODO(kdy1): This is bad. self.base .serialize(serde::__private::ser::FlatMapSerializer(&mut s))?; } s.serialize_entry("type", "MethodDefinition")?; s.serialize_entry("computed", &self.computed.unwrap_or(false))?; s.serialize_entry("key", &self.key)?; s.serialize_entry("kind", &self.kind)?; s.serialize_entry("static", &self.is_static.unwrap_or(false))?; s.serialize_entry( "value", &AcornClassMethodValue { type_: "FunctionExpression", base: &self.body.base, body: &self.body, params: &self.params, generator: self.generator.unwrap_or(false), is_async: self.is_async.unwrap_or(false), }, )?; s.end() } } } } #[derive(Debug, Clone, PartialEq)] #[ast_serde("ClassPrivateProperty")] pub struct ClassPrivateProperty { #[serde(flatten)] pub base: BaseNode, pub key: PrivateName, #[serde(default)] pub value: Option<Box<Expression>>, #[serde(default)] pub decorators: Option<Vec<Decorator>>, #[serde(default, rename = "static")] pub static_any: Value, #[serde(default)] pub type_annotation: Option<Box<TypeAnnotOrNoop>>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("ClassPrivateMethod")] pub struct ClassPrivateMethod { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub kind: Option<ClassMethodKind>, pub key: PrivateName, #[serde(default)] pub params: Vec<Param>, pub body: BlockStatement, #[serde(default, rename = "static")] pub is_static: Option<bool>, #[serde(default, rename = "abstract")] pub is_abstract: Option<bool>, #[serde(default)] pub access: Option<Access>, #[serde(default)] pub accessibility: Option<Access>, #[serde(default, rename = "async")] pub is_async: Option<bool>, #[serde(default)] pub computed: Option<bool>, #[serde(default)] pub decorators: Option<Vec<Decorator>>, #[serde(default)] pub generator: Option<bool>, #[serde(default)] pub optional: Option<bool>, #[serde(default)] pub return_type: Option<Box<TypeAnnotOrNoop>>, #[serde(default)] pub type_parameters: Option<TypeParamDeclOrNoop>, } #[derive(Debug, Clone, PartialEq, Deserialize)] pub struct ClassProperty { #[serde(flatten)] pub base: BaseNode, pub key: ObjectKey, #[serde(default)] pub value: Option<Box<Expression>>, #[serde(default)] pub type_annotation: Option<Box<TypeAnnotOrNoop>>, #[serde(default)] pub decorators: Option<Vec<Decorator>>, #[serde(default)] pub computed: Option<bool>, #[serde(default, rename = "static")] pub is_static: Option<bool>, #[serde(default, rename = "abstract")] pub is_abstract: Option<bool>, #[serde(default)] pub accessibility: Option<Access>, #[serde(default)] pub declare: Option<bool>, #[serde(default)] pub definite: Option<bool>, #[serde(default)] pub optional: Option<bool>, #[serde(default)] pub readonly: Option<bool>, } #[derive(Serialize)] struct BabelClassProperty<'a> { #[serde(rename = "type")] type_: &'static str, #[serde(flatten)] pub base: &'a BaseNode, pub key: &'a ObjectKey, #[serde(default)] pub value: Option<&'a Expression>, #[serde(default)] pub type_annotation: Option<&'a TypeAnnotOrNoop>, #[serde(default)] pub decorators: Option<&'a [Decorator]>, #[serde(default)] pub computed: Option<bool>, #[serde(default, rename = "static")] pub is_static: Option<bool>, #[serde(default, rename = "abstract")] pub is_abstract: Option<bool>, #[serde(default)] pub accessibility: Option<&'a Access>, #[serde(default)] pub declare: Option<bool>, #[serde(default)] pub definite: Option<bool>, #[serde(default)] pub optional: Option<bool>, #[serde(default)] pub readonly: Option<bool>, } impl Serialize for ClassProperty { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { match Flavor::current() { Flavor::Babel => { let actual = BabelClassProperty { type_: "ClassProperty", base: &self.base, key: &self.key, value: self.value.as_deref(), type_annotation: self.type_annotation.as_deref(), decorators: self.decorators.as_deref(), computed: self.computed, is_static: self.is_static, is_abstract: self.is_abstract, accessibility: self.accessibility.as_ref(), declare: self.declare, definite: self.definite, optional: self.optional, readonly: self.readonly, }; actual.serialize(serializer) } Flavor::Acorn { .. } => { let mut s = serializer.serialize_map(None)?; { // TODO(kdy1): This is bad. self.base .serialize(serde::__private::ser::FlatMapSerializer(&mut s))?; } s.serialize_entry("type", "PropertyDefinition")?; s.serialize_entry("static", &self.is_static)?; s.serialize_entry("key", &self.key)?; s.serialize_entry("value", &self.value)?; s.serialize_entry("computed", &self.computed)?; if let Some(decorators) = &self.decorators { if !decorators.is_empty() { s.serialize_entry("decorators", decorators)?; } } s.serialize_entry("computed", &self.computed)?; s.end() } } } } #[derive(Debug, Clone, PartialEq)] #[ast_serde("StaticBlock")] pub struct StaticBlock { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub body: Vec<Statement>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ClassBodyEl { #[tag("ClassMethod")] Method(ClassMethod), #[tag("ClassPrivateMethod")] PrivateMethod(ClassPrivateMethod), #[tag("ClassProperty")] Prop(ClassProperty), #[tag("ClassPrivateProperty")] PrivateProp(ClassPrivateProperty), #[tag("TSDeclareMethod")] TSMethod(TSDeclareMethod), #[tag("TSIndexSignature")] TSIndex(TSIndexSignature), #[tag("StaticBlock")] StaticBlock(StaticBlock), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("ClassBody")] pub struct ClassBody { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub body: Vec<ClassBodyEl>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ClassImpl { #[tag("TSExpressionWithTypeArguments")] TSExpr(TSExpressionWithTypeArguments), #[tag("ClassImplements")] Implements(ClassImplements), } impl From<TSExpressionWithTypeArguments> for ClassImpl { fn from(expr: TSExpressionWithTypeArguments) -> Self { ClassImpl::TSExpr(expr) } } #[derive(Debug, Clone, PartialEq)] #[ast_serde("ClassDeclaration")] pub struct ClassDeclaration { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, #[serde(default)] pub super_class: Option<Box<Expression>>, pub body: ClassBody, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_empty")] pub decorators: Option<Vec<Decorator>>, #[serde( default, rename = "abstract", skip_serializing_if = "crate::ser::skip_typescript" )] pub is_abstract: Option<bool>, #[serde(default, skip_serializing_if = "crate::ser::skip_typescript")] pub declare: Option<bool>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_empty")] pub implements: Option<Vec<ClassImpl>>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub mixins: Option<InterfaceExtends>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub super_type_parameters: Option<SuperTypeParams>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub type_parameters: Option<TypeParamDeclOrNoop>, } impl From<ClassExpression> for ClassDeclaration { fn from(expr: ClassExpression) -> Self { ClassDeclaration { base: expr.base, id: expr.id.unwrap(), super_class: expr.super_class.map(|s| Box::new(*s)), body: expr.body, decorators: expr.decorators, is_abstract: Default::default(), declare: Default::default(), implements: expr.implements, mixins: expr.mixins, super_type_parameters: expr.super_type_parameters, type_parameters: expr.type_parameters, } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_ast/src/comment.rs
Rust
use serde::{Deserialize, Serialize}; use swc_atoms::Atom; use swc_common::ast_serde; use crate::common::Loc; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum CommentType { #[serde(rename = "CommentLine")] Line, #[serde(rename = "CommentBlock")] Block, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct BaseComment { #[serde(rename = "type")] pub type_: CommentType, pub value: Atom, pub start: u32, pub end: u32, pub loc: Loc, } #[derive(Debug, Clone, PartialEq, Eq)] #[ast_serde] pub enum Comment { #[tag("CommentBlock")] Block(BaseComment), #[tag("CommentLine")] Line(BaseComment), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum CommentTypeShorthand { Leading, Inner, Trailing, }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_ast/src/common.rs
Rust
use serde::{Deserialize, Serialize}; use swc_atoms::Atom; use swc_common::ast_serde; use crate::{ class::*, comment::Comment, decl::*, expr::*, flow::*, jsx::*, lit::*, module::*, object::*, pat::*, stmt::*, typescript::*, }; #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct LineCol { pub line: usize, pub column: usize, } impl LineCol { pub fn dummy() -> Self { LineCol { line: 0, column: 0 } } } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct Loc { pub start: LineCol, pub end: LineCol, } impl Loc { pub fn dummy() -> Self { Loc { start: LineCol::dummy(), end: LineCol::dummy(), } } } #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde-impl", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde-impl", serde(rename_all = "camelCase"))] pub struct BaseNode { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub leading_comments: Vec<Comment>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub inner_comments: Vec<Comment>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub trailing_comments: Vec<Comment>, #[serde(default)] pub start: Option<u32>, #[serde(default)] pub end: Option<u32>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_range")] pub range: Option<[u32; 2]>, #[serde(default)] pub loc: Option<Loc>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Binary { #[tag("BinaryExpression")] BinaryExpr(BinaryExpression), #[tag("LogicalExpression")] LogicalExpr(LogicalExpression), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Conditional { #[tag("ConditionalExpression")] Expr(ConditionalExpression), #[tag("IfStatement")] If(IfStatement), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Function { #[tag("FunctionDeclaration")] Decl(FunctionDeclaration), #[tag("FunctionExpression")] Expr(FunctionExpression), #[tag("ObjectMethod")] ObjectMethod(ObjectMethod), #[tag("ArrowFunctionExpression")] Arrow(ArrowFunctionExpression), #[tag("ClassMethod")] ClassMethod(ClassMethod), #[tag("ClassPrivateMethod")] ClassPrivateMethod(ClassPrivateMethod), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum FunctionParent { #[tag("FunctionDeclaration")] Decl(FunctionDeclaration), #[tag("FunctionExpression")] Expr(FunctionExpression), #[tag("ObjectMethod")] ObjectMethod(ObjectMethod), #[tag("ArrowFunctionExpression")] Arrow(ArrowFunctionExpression), #[tag("ClassMethod")] ClassMethod(ClassMethod), #[tag("ClassPrivateMethod")] ClassPrivateMethod(ClassPrivateMethod), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Immutable { #[tag("StringLiteral")] #[tag("DecimalLiteral")] #[tag("NumericLiteral")] #[tag("NullLiteral")] #[tag("BooleanLiteral")] #[tag("BigIntLiteral")] Literal(Literal), #[tag("JSXAttribute")] JSXAttribute(JSXAttribute), #[tag("JSXClosingElement")] JSXClosingElement(JSXClosingElement), #[tag("JSXElement")] JSXElement(JSXElement), #[tag("JSXExpressionContainer")] JSXExpressionContainer(JSXExpressionContainer), #[tag("JSXSpreadChild")] JSXSpreadChild(JSXSpreadChild), #[tag("JSXOpeningElement")] JSXOpeningElement(JSXOpeningElement), #[tag("JSXText")] JSXText(JSXText), #[tag("JSXFragment")] JSXFragment(JSXFragment), #[tag("JSXOpeningFragment")] JSXOpeningFragment(JSXOpeningFragment), #[tag("JSXClosingFragment")] JSXClosingFragment(JSXClosingFragment), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Method { #[tag("ObjectMethod")] Object(ObjectMethod), #[tag("ClassMethod")] Class(ClassMethod), #[tag("ClassPrivateMethod")] ClassPrivate(ClassPrivateMethod), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Private { #[tag("ClassPrivateProperty")] ClassProp(ClassPrivateProperty), #[tag("ClassPrivateMethod")] ClassMethod(ClassPrivateMethod), #[tag("PrivateName")] Name(PrivateName), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Property { #[tag("ObjectProperty")] ObjectProp(ObjectProperty), #[tag("ClassProperty")] ClassProp(ClassProperty), #[tag("ClassPrivateProperty")] ClassPrivateProp(ClassPrivateProperty), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Pureish { #[tag("FunctionDeclaration")] FunctionDecl(FunctionDeclaration), #[tag("FunctionExpression")] FunctionExpr(FunctionExpression), #[tag("StringLiteral")] #[tag("NumericLiteral")] #[tag("NullLiteral")] #[tag("BooleanLiteral")] #[tag("RegExpLiteral")] #[tag("BigIntLiteral")] #[tag("DecimalLiteral")] Literal(Literal), #[tag("ArrowFunctionExpression")] ArrowFuncExpr(ArrowFunctionExpression), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Scopable { #[tag("BlockStatement")] BlockStmt(BlockStatement), #[tag("CatchClause")] CatchClause(CatchClause), #[tag("DoWhileStatement")] DoWhileStmt(DoWhileStatement), #[tag("ForInStatement")] ForInStmt(ForInStatement), #[tag("ForStatement")] ForStmt(ForStatement), #[tag("FunctionDeclaration")] FuncDecl(FunctionDeclaration), #[tag("FunctionExpression")] FuncExpr(FunctionExpression), #[tag("Program")] Program(Program), #[tag("ObjectMethod")] ObjectMethod(ObjectMethod), #[tag("SwitchStatement")] SwitchStmt(SwitchStatement), #[tag("WhileStatement")] WhileStmt(WhileStatement), #[tag("ArrowFunctionExpression")] ArrowFuncExpr(ArrowFunctionExpression), #[tag("ClassExpression")] ClassExpr(ClassExpression), #[tag("ClassDeclaration")] ClassDecl(ClassDeclaration), #[tag("ForOfStatement")] ForOfStmt(ForOfStatement), #[tag("ClassMethod")] ClassMethod(ClassMethod), #[tag("ClassPrivateMethod")] ClassPrivateMethod(ClassPrivateMethod), #[tag("StaticBlock")] StaticBlock(StaticBlock), #[tag("TSModuleBlock")] TSModuleBlock(TSModuleBlock), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum BlockParent { #[tag("BlockStatement")] BlockStmt(BlockStatement), #[tag("CatchClause")] CatchClause(CatchClause), #[tag("DoWhileStatement")] DoWhileStmt(DoWhileStatement), #[tag("ForInStatement")] ForInStmt(ForInStatement), #[tag("ForStatement")] ForStmt(ForStatement), #[tag("FunctionDeclaration")] FuncDecl(FunctionDeclaration), #[tag("FunctionExpression")] FuncExpr(FunctionExpression), #[tag("Program")] Program(Program), #[tag("ObjectMethod")] ObjectMethod(ObjectMethod), #[tag("SwitchStatement")] SwitchStmt(SwitchStatement), #[tag("WhileStatement")] WhileStmt(WhileStatement), #[tag("ArrowFunctionExpression")] ArrowFuncExpr(ArrowFunctionExpression), #[tag("ForOfStatement")] ForOfStmt(ForOfStatement), #[tag("ClassMethod")] ClassMethod(ClassMethod), #[tag("ClassPrivateMethod")] ClassPrivateMethod(ClassPrivateMethod), #[tag("StaticBlock")] StaticBlock(StaticBlock), #[tag("TSModuleBlock")] TSModuleBlock(TSModuleBlock), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Block { #[tag("BlockStatement")] BlockStmt(BlockStatement), #[tag("Program")] Program(Program), #[tag("TSModuleBlock")] TSModuleBlock(TSModuleBlock), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Terminatorless { #[tag("BreakStatement")] Break(BreakStatement), #[tag("ContinueStatement")] Continue(ContinueStatement), #[tag("ReturnStatement")] Return(ReturnStatement), #[tag("ThrowStatement")] Throw(ThrowStatement), #[tag("YieldExpression")] Yield(YieldExpression), #[tag("AwaitExpression")] Await(AwaitExpression), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum UnaryLike { #[tag("UnaryExpression")] Expr(UnaryExpression), #[tag("SpreadElement")] Spread(SpreadElement), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("SpreadElement")] pub struct SpreadElement { #[serde(flatten)] pub base: BaseNode, pub argument: Box<Expression>, } /// Deprecated. Use SpreadElement instead. #[derive(Debug, Clone, PartialEq)] #[ast_serde("SpreadProperty")] pub struct SpreadProperty { #[serde(flatten)] pub base: BaseNode, pub argument: Box<Expression>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("RestElement")] pub struct RestElement { #[serde(flatten)] pub base: BaseNode, pub argument: Box<LVal>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_empty")] pub decorators: Option<Vec<Decorator>>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub type_annotation: Option<Box<TypeAnnotOrNoop>>, } /// Deprecated. Use RestElement element. #[derive(Debug, Clone, PartialEq)] #[ast_serde("RestProperty")] pub struct RestProperty { #[serde(flatten)] pub base: BaseNode, pub argument: LVal, #[serde(default)] pub decorators: Option<Vec<Decorator>>, #[serde(default)] pub type_annotation: Option<Box<TypeAnnotOrNoop>>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("Identifier")] pub struct Identifier { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub name: Atom, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_empty")] pub decorators: Option<Vec<Decorator>>, #[serde( default, skip_serializing_if = "crate::flavor::Flavor::skip_none_and_false" )] pub optional: Option<bool>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub type_annotation: Option<Box<TypeAnnotOrNoop>>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum IdOrQualifiedId { #[tag("Identifier")] Id(Identifier), #[tag("QualifiedTypeIdentifier")] QualifiedId(QualifiedTypeIdentifier), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum IdOrString { #[tag("Identifier")] Id(Identifier), #[tag("StringLiteral")] String(StringLiteral), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum IdOrRest { #[tag("Identifier")] Id(Identifier), #[tag("RestElement")] Rest(RestElement), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("Decorator")] pub struct Decorator { #[serde(flatten)] pub base: BaseNode, pub expression: Box<Expression>, } #[derive(Debug, Clone, PartialEq, Eq)] #[ast_serde("Noop")] pub struct Noop { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Param { #[tag("Identifier")] Id(Identifier), #[tag("AssignmentPattern")] #[tag("ArrayPattern")] #[tag("ObjectPattern")] Pat(Pattern), #[tag("RestElement")] Rest(RestElement), #[tag("TSParameterProperty")] TSProp(TSParameterProperty), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum LVal { #[tag("Identifier")] Id(Identifier), #[tag("MemberExpression")] MemberExpr(MemberExpression), #[tag("RestElement")] RestEl(RestElement), #[tag("AssignmentPattern")] AssignmentPat(AssignmentPattern), #[tag("ArrayPattern")] ArrayPat(ArrayPattern), #[tag("ObjectPattern")] ObjectPat(ObjectPattern), #[tag("TSParameterProperty")] TSParamProp(TSParameterProperty), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum PatternLike { #[tag("Identifier")] Id(Identifier), #[tag("RestElement")] RestEl(RestElement), #[tag("AssignmentPattern")] AssignmentPat(AssignmentPattern), #[tag("ArrayPattern")] ArrayPat(ArrayPattern), #[tag("ObjectPattern")] ObjectPat(ObjectPattern), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum TypeAnnotOrNoop { #[tag("TypeAnnotation")] Flow(TypeAnnotation), #[tag("TSTypeAnnotation")] TS(Box<TSTypeAnnotation>), #[tag("Noop")] Noop(Noop), } impl From<TSTypeAnnotation> for TypeAnnotOrNoop { fn from(annot: TSTypeAnnotation) -> Self { TypeAnnotOrNoop::TS(Box::new(annot)) } } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum TypeParamDeclOrNoop { #[tag("TypeParameterDeclaration")] Flow(TypeParameterDeclaration), #[tag("TSTypeParameterDeclaration")] TS(TSTypeParameterDeclaration), #[tag("Noop")] Noop(Noop), } impl From<TSTypeParameterDeclaration> for TypeParamDeclOrNoop { fn from(decl: TSTypeParameterDeclaration) -> Self { TypeParamDeclOrNoop::TS(decl) } } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum SuperTypeParams { #[tag("TypeParameterInstantiation")] Flow(TypeParameterInstantiation), #[tag("TSTypeParameterInstantiation")] TS(TSTypeParameterInstantiation), } impl From<TSTypeParameterInstantiation> for SuperTypeParams { fn from(param: TSTypeParameterInstantiation) -> Self { SuperTypeParams::TS(param) } } #[derive(Debug, Clone, PartialEq)] #[ast_serde("PrivateName")] pub struct PrivateName { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum Access { Public, Private, Protected, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("MetaProperty")] pub struct MetaProperty { #[serde(flatten)] pub base: BaseNode, pub meta: Identifier, pub property: Identifier, } #[derive(Debug, Clone, PartialEq, Eq)] #[ast_serde("Directive")] pub struct Directive { #[serde(flatten)] pub base: BaseNode, pub value: DirectiveLiteral, } #[derive(Debug, Clone, PartialEq, Eq)] #[ast_serde("DirectiveLiteral")] pub struct DirectiveLiteral { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub value: Atom, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("PipelineBareFunction")] pub struct PipelineBareFunction { #[serde(flatten)] pub base: BaseNode, pub callee: Box<Expression>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("PipelineTopicExpression")] pub struct PipelineTopicExpression { #[serde(flatten)] pub base: BaseNode, pub expression: Box<Expression>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub enum PlaceholderExpectedNode { Identifier, StringLiteral, Expression, Statement, Declaration, BlockStatement, ClassBody, Pattern, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("Placeholder")] pub struct Placeholder { #[serde(flatten)] pub base: BaseNode, pub expected_node: PlaceholderExpectedNode, pub name: Identifier, } // NOTE(dwoznicki): Node is part of the babel node definitions, but it's never // used and a pain to maintain. Do we actually need this? // // #[derive(Debug, Clone, PartialEq)] // #[ast_serde] // pub enum Node { // #[tag("AnyTypeAnnotation")] // AnyTypeAnnotation(AnyTypeAnnotation), // #[tag("ArgumentPlaceholder")] // ArgumentPlaceholder(ArgumentPlaceholder), // #[tag("ArrayExpression")] // ArrayExpression(ArrayExpression), // #[tag("ArrayPattern")] // ArrayPattern(ArrayPattern), // #[tag("ArrayTypeAnnotation")] // ArrayTypeAnnotation(ArrayTypeAnnotation), // #[tag("ArrowFunctionExpression")] // ArrowFunctionExpression(ArrowFunctionExpression), // #[tag("AssignmentExpression")] // AssignmentExpression(AssignmentExpression), // #[tag("AssignmentPattern")] // AssignmentPattern(AssignmentPattern), // #[tag("AwaitExpression")] // AwaitExpression(AwaitExpression), // #[tag("BigIntLiteral")] // BigIntLiteral(BigIntLiteral), // #[tag("BinaryExpression")] // #[tag("LogicalExpression")] // Binary(Binary), // #[tag("BinaryExpression")] // BinaryExpression(BinaryExpression), // #[tag("BindExpression")] // BindExpression(BindExpression), // #[tag("BlockStatement")] // #[tag("Program")] // #[tag("TSModuleBlock")] // Block(Block), // #[tag("*")] // BlockParent(BlockParent), // #[tag("BlockStatement")] // BlockStatement(BlockStatement), // BooleanLiteral(BooleanLiteral), // BooleanLiteralTypeAnnotation(BooleanLiteralTypeAnnotation), // BooleanTypeAnnotation(BooleanTypeAnnotation), // BreakStatement(BreakStatement), // CallExpression(CallExpression), // CatchClause(CatchClause), // Class(Class), // ClassBody(ClassBody), // ClassDeclaration(ClassDeclaration), // ClassExpression(ClassExpression), // ClassImplements(ClassImplements), // ClassMethod(ClassMethod), // ClassPrivateMethod(ClassPrivateMethod), // ClassPrivateProperty(ClassPrivateProperty), // ClassProperty(ClassProperty), // CompletionStatement(CompletionStatement), // Conditional(Conditional), // ConditionalExpression(ConditionalExpression), // ContinueStatement(ContinueStatement), // DebuggerStatement(DebuggerStatement), // DecimalLiteral(DecimalLiteral), // Declaration(Declaration), // DeclareClass(DeclareClass), // DeclareExportAllDeclaration(DeclareExportAllDeclaration), // DeclareExportDeclaration(DeclareExportDeclaration), // DeclareFunction(DeclareFunction), // DeclareInterface(DeclareInterface), // DeclareModule(DeclareModule), // DeclareModuleExports(DeclareModuleExports), // DeclareOpaqueType(DeclareOpaqueType), // DeclareTypeAlias(DeclareTypeAlias), // DeclareVariable(DeclareVariable), // DeclaredPredicate(DeclaredPredicate), // Decorator(Decorator), // Directive(Directive), // DirectiveLiteral(DirectiveLiteral), // DoExpression(DoExpression), // DoWhileStatement(DoWhileStatement), // EmptyStatement(EmptyStatement), // EmptyTypeAnnotation(EmptyTypeAnnotation), // EnumBody(EnumBody), // EnumBooleanBody(EnumBooleanBody), // EnumBooleanMember(EnumBooleanMember), // EnumDeclaration(EnumDeclaration), // EnumDefaultedMember(EnumDefaultedMember), // EnumMember(EnumMember), // EnumNumberBody(EnumNumberBody), // EnumNumberMember(EnumNumberMember), // EnumStringBody(EnumStringBody), // EnumStringMember(EnumStringMember), // EnumSymbolBody(EnumSymbolBody), // ExistsTypeAnnotation(ExistsTypeAnnotation), // ExportAllDeclaration(ExportAllDeclaration), // ExportDeclaration(ExportDeclaration), // ExportDefaultDeclaration(ExportDefaultDeclaration), // ExportDefaultSpecifier(ExportDefaultSpecifier), // ExportNamedDeclaration(ExportNamedDeclaration), // ExportNamespaceSpecifier(ExportNamespaceSpecifier), // ExportSpecifier(ExportSpecifier), // Expression(Expression), // ExpressionStatement(ExpressionStatement), // ExpressionWrapper(ExpressionWrapper), // File(File), // Flow(Flow), // FlowBaseAnnotation(FlowBaseAnnotation), // FlowDeclaration(FlowDeclaration), // FlowPredicate(FlowPredicate), // FlowType(FlowType), // For(For), // ForInStatement(ForInStatement), // ForOfStatement(ForOfStatement), // ForStatement(ForStatement), // ForXStatement(ForXStatement), // Function(Function), // FunctionDeclaration(FunctionDeclaration), // FunctionExpression(FunctionExpression), // FunctionParent(FunctionParent), // FunctionTypeAnnotation(FunctionTypeAnnotation), // FunctionTypeParam(FunctionTypeParam), // GenericTypeAnnotation(GenericTypeAnnotation), // Identifier(Identifier), // IfStatement(IfStatement), // Immutable(Immutable), // Import(Import), // ImportAttribute(ImportAttribute), // ImportDeclaration(ImportDeclaration), // ImportDefaultSpecifier(ImportDefaultSpecifier), // ImportNamespaceSpecifier(ImportNamespaceSpecifier), // ImportSpecifier(ImportSpecifier), // InferredPredicate(InferredPredicate), // InterfaceDeclaration(InterfaceDeclaration), // InterfaceExtends(InterfaceExtends), // InterfaceTypeAnnotation(InterfaceTypeAnnotation), // InterpreterDirective(InterpreterDirective), // IntersectionTypeAnnotation(IntersectionTypeAnnotation), // JSX(JSX), // JSXAttribute(JSXAttribute), // JSXClosingElement(JSXClosingElement), // JSXClosingFragment(JSXClosingFragment), // JSXElement(JSXElement), // JSXEmptyExpression(JSXEmptyExpression), // JSXExpressionContainer(JSXExpressionContainer), // JSXFragment(JSXFragment), // JSXIdentifier(JSXIdentifier), // JSXMemberExpression(JSXMemberExpression), // JSXNamespacedName(JSXNamespacedName), // JSXOpeningElement(JSXOpeningElement), // JSXOpeningFragment(JSXOpeningFragment), // JSXSpreadAttribute(JSXSpreadAttribute), // JSXSpreadChild(JSXSpreadChild), // JSXText(JSXText), // LVal(LVal), // LabeledStatement(LabeledStatement), // Literal(Literal), // LogicalExpression(LogicalExpression), // Loop(Loop), // MemberExpression(MemberExpression), // MetaProperty(MetaProperty), // Method(Method), // MixedTypeAnnotation(MixedTypeAnnotation), // ModuleDeclaration(ModuleDeclaration), // ModuleExpression(ModuleExpression), // ModuleSpecifier(ModuleSpecifier), // NewExpression(NewExpression), // Noop(Noop), // NullLiteral(NullLiteral), // NullLiteralTypeAnnotation(NullLiteralTypeAnnotation), // NullableTypeAnnotation(NullableTypeAnnotation), // NumberLiteral(NumberLiteral), // NumberLiteralTypeAnnotation(NumberLiteralTypeAnnotation), // NumberTypeAnnotation(NumberTypeAnnotation), // NumericLiteral(NumericLiteral), // ObjectExpression(ObjectExpression), // ObjectMember(ObjectMember), // ObjectMethod(ObjectMethod), // ObjectPattern(ObjectPattern), // ObjectProperty(ObjectProperty), // ObjectTypeAnnotation(ObjectTypeAnnotation), // ObjectTypeCallProperty(ObjectTypeCallProperty), // ObjectTypeIndexer(ObjectTypeIndexer), // ObjectTypeInternalSlot(ObjectTypeInternalSlot), // ObjectTypeProperty(ObjectTypeProperty), // ObjectTypeSpreadProperty(ObjectTypeSpreadProperty), // OpaqueType(OpaqueType), // OptionalCallExpression(OptionalCallExpression), // OptionalMemberExpression(OptionalMemberExpression), // ParenthesizedExpression(ParenthesizedExpression), // Pattern(Pattern), // PatternLike(PatternLike), // PipelineBareFunction(PipelineBareFunction), // PipelinePrimaryTopicReference(PipelinePrimaryTopicReference), // PipelineTopicExpression(PipelineTopicExpression), // Placeholder(Placeholder), // Private(Private), // PrivateName(PrivateName), // Program(Program), // Property(Property), // Pureish(Pureish), // QualifiedTypeIdentifier(QualifiedTypeIdentifier), // RecordExpression(RecordExpression), // RegExpLiteral(RegExpLiteral), // RegexLiteral(RegexLiteral), // RestElement(RestElement), // RestProperty(RestProperty), // ReturnStatement(ReturnStatement), // Scopable(Scopable), // SequenceExpression(SequenceExpression), // SpreadElement(SpreadElement), // SpreadProperty(SpreadProperty), // Statement(Statement), // StaticBlock(StaticBlock), // StringLiteral(StringLiteral), // StringLiteralTypeAnnotation(StringLiteralTypeAnnotation), // StringTypeAnnotation(StringTypeAnnotation), // Super(Super), // SwitchCase(SwitchCase), // SwitchStatement(SwitchStatement), // SymbolTypeAnnotation(SymbolTypeAnnotation), // TSAnyKeyword(TSAnyKeyword), // TSArrayType(TSArrayType), // TSAsExpression(TSAsExpression), // TSBaseType(TSBaseType), // TSBigIntKeyword(TSBigIntKeyword), // TSBooleanKeyword(TSBooleanKeyword), // TSCallSignatureDeclaration(TSCallSignatureDeclaration), // TSConditionalType(TSConditionalType), // TSConstructSignatureDeclaration(TSConstructSignatureDeclaration), // TSConstructorType(TSConstructorType), // TSDeclareFunction(TSDeclareFunction), // TSDeclareMethod(TSDeclareMethod), // TSEntityName(TSEntityName), // TSEnumDeclaration(TSEnumDeclaration), // TSEnumMember(TSEnumMember), // TSExportAssignment(TSExportAssignment), // TSExpressionWithTypeArguments(TSExpressionWithTypeArguments), // TSExternalModuleReference(TSExternalModuleReference), // TSFunctionType(TSFunctionType), // TSImportEqualsDeclaration(TSImportEqualsDeclaration), // TSImportType(TSImportType), // TSIndexSignature(TSIndexSignature), // TSIndexedAccessType(TSIndexedAccessType), // TSInferType(TSInferType), // TSInterfaceBody(TSInterfaceBody), // TSInterfaceDeclaration(TSInterfaceDeclaration), // TSIntersectionType(TSIntersectionType), // TSIntrinsicKeyword(TSIntrinsicKeyword), // TSLiteralType(TSLiteralType), // TSMappedType(TSMappedType), // TSMethodSignature(TSMethodSignature), // TSModuleBlock(TSModuleBlock), // TSModuleDeclaration(TSModuleDeclaration), // TSNamedTupleMember(TSNamedTupleMember), // TSNamespaceExportDeclaration(TSNamespaceExportDeclaration), // TSNeverKeyword(TSNeverKeyword), // TSNonNullExpression(TSNonNullExpression), // TSNullKeyword(TSNullKeyword), // TSNumberKeyword(TSNumberKeyword), // TSObjectKeyword(TSObjectKeyword), // TSOptionalType(TSOptionalType), // TSParameterProperty(TSParameterProperty), // TSParenthesizedType(TSParenthesizedType), // TSPropertySignature(TSPropertySignature), // TSQualifiedName(TSQualifiedName), // TSRestType(TSRestType), // TSStringKeyword(TSStringKeyword), // TSSymbolKeyword(TSSymbolKeyword), // TSThisType(TSThisType), // TSTupleType(TSTupleType), // TSType(TSType), // TSTypeAliasDeclaration(TSTypeAliasDeclaration), // TSTypeAnnotation(TSTypeAnnotation), // TSTypeAssertion(TSTypeAssertion), // TSTypeElement(TSTypeElement), // TSTypeLiteral(TSTypeLiteral), // TSTypeOperator(TSTypeOperator), // TSTypeParameter(TSTypeParameter), // TSTypeParameterDeclaration(TSTypeParameterDeclaration), // TSTypeParameterInstantiation(TSTypeParameterInstantiation), // TSTypePredicate(TSTypePredicate), // TSTypeQuery(TSTypeQuery), // TSTypeReference(TSTypeReference), // TSUndefinedKeyword(TSUndefinedKeyword), // TSUnionType(TSUnionType), // TSUnknownKeyword(TSUnknownKeyword), // TSVoidKeyword(TSVoidKeyword), // TaggedTemplateExpression(TaggedTemplateExpression), // TemplateElement(TemplateElement), // TemplateLiteral(TemplateLiteral), // Terminatorless(Terminatorless), // ThisExpression(ThisExpression), // ThisTypeAnnotation(ThisTypeAnnotation), // ThrowStatement(ThrowStatement), // TryStatement(TryStatement), // TupleExpression(TupleExpression), // TupleTypeAnnotation(TupleTypeAnnotation), // TypeAlias(TypeAlias), // TypeAnnotation(TypeAnnotation), // TypeCastExpression(TypeCastExpression), // TypeParameter(TypeParameter), // TypeParameterDeclaration(TypeParameterDeclaration), // TypeParameterInstantiation(TypeParameterInstantiation), // TypeofTypeAnnotation(TypeofTypeAnnotation), // UnaryExpression(UnaryExpression), // UnaryLike(UnaryLike), // UnionTypeAnnotation(UnionTypeAnnotation), // UpdateExpression(UpdateExpression), // UserWhitespacable(UserWhitespacable), // V8IntrinsicIdentifier(V8IntrinsicIdentifier), // VariableDeclaration(VariableDeclaration), // VariableDeclarator(VariableDeclarator), // Variance(Variance), // VoidTypeAnnotation(VoidTypeAnnotation), // While(While), // WhileStatement(WhileStatement), // WithStatement(WithStatement), // YieldExpression(YieldExpression), // }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_ast/src/decl.rs
Rust
use serde::{Deserialize, Serialize}; use swc_common::ast_serde; use crate::{ class::ClassDeclaration, common::{BaseNode, Identifier, LVal, Param, TypeAnnotOrNoop, TypeParamDeclOrNoop}, expr::{Expression, FunctionExpression}, flow::{ DeclareClass, DeclareExportAllDeclaration, DeclareExportDeclaration, DeclareFunction, DeclareInterface, DeclareModule, DeclareModuleExports, DeclareOpaqueType, DeclareTypeAlias, DeclareVariable, InterfaceDeclaration, OpaqueType, TypeAlias, }, lit::{BooleanLiteral, NumericLiteral, StringLiteral}, module::{ ExportAllDeclaration, ExportDefaultDeclaration, ExportNamedDeclaration, ImportDeclaration, }, stmt::BlockStatement, typescript::{ TSDeclareFunction, TSEnumDeclaration, TSInterfaceDeclaration, TSModuleDeclaration, TSTypeAliasDeclaration, }, }; #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Declaration { #[tag("FunctionDeclaration")] FuncDecl(FunctionDeclaration), #[tag("VariableDeclaration")] VarDecl(VariableDeclaration), #[tag("UsingDeclaration")] UsingDecl(UsingDeclaration), #[tag("ClassDeclaration")] ClassDecl(ClassDeclaration), #[tag("ExportAllDeclaration")] ExportAllDecl(ExportAllDeclaration), #[tag("ExportDefaultDeclaration")] ExportDefaultDecl(ExportDefaultDeclaration), #[tag("ExportNamedDeclaration")] ExportNamedDecl(ExportNamedDeclaration), #[tag("ImportDeclaration")] ImportDecl(ImportDeclaration), #[tag("DeclareClass")] DeclClass(DeclareClass), #[tag("DeclareFunction")] DeclFunc(DeclareFunction), #[tag("DeclareInterface")] DeclInterface(DeclareInterface), #[tag("DeclareModule")] DeclModule(DeclareModule), #[tag("DeclareModuleExports")] DeclModuleExports(DeclareModuleExports), #[tag("DeclareTypeAlias")] DeclTypeAlias(DeclareTypeAlias), #[tag("DeclareOpaqueType")] DeclOpaqueType(DeclareOpaqueType), #[tag("DeclareVariable")] DeclVar(DeclareVariable), #[tag("DeclareExportDeclaration")] DeclExportDecl(DeclareExportDeclaration), #[tag("DeclareExportAllDeclaration")] DeclExportAllDecl(DeclareExportAllDeclaration), #[tag("InterfaceDeclaration")] InterfaceDecl(InterfaceDeclaration), #[tag("OpaqueType")] OpaqueType(OpaqueType), #[tag("TypeAlias")] TypeAlias(TypeAlias), #[tag("EnumDeclaration")] EnumDecl(EnumDeclaration), #[tag("TSDeclareFunction")] TSDeclFunc(TSDeclareFunction), #[tag("TSInterfaceDeclaration")] TSInterfaceDecl(TSInterfaceDeclaration), #[tag("TSTypeAliasDeclaration")] TSTypeAliasDecl(TSTypeAliasDeclaration), #[tag("TSEnumDeclaration")] TSEnumDecl(TSEnumDeclaration), #[tag("TSModuleDeclaration")] TSModuleDecl(TSModuleDeclaration), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum VariableDeclarationKind { Var, Let, Const, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("VariableDeclarator")] pub struct VariableDeclarator { #[serde(flatten)] pub base: BaseNode, pub id: LVal, #[serde(default)] pub init: Option<Box<Expression>>, #[serde( default, skip_serializing_if = "crate::flavor::Flavor::skip_none_and_false" )] pub definite: Option<bool>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("VariableDeclaration")] pub struct VariableDeclaration { #[serde(flatten)] pub base: BaseNode, pub kind: VariableDeclarationKind, #[serde(default)] pub declarations: Vec<VariableDeclarator>, #[serde( default, skip_serializing_if = "crate::flavor::Flavor::skip_none_and_false" )] pub declare: Option<bool>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("FunctionDeclaration")] pub struct FunctionDeclaration { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub id: Option<Identifier>, #[serde(default)] pub params: Vec<Param>, pub body: BlockStatement, #[serde(default)] pub generator: Option<bool>, #[serde(default, rename = "async")] pub is_async: Option<bool>, #[serde(default, skip_serializing_if = "crate::ser::skip_expression_for_fn")] pub expression: bool, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub return_type: Option<Box<TypeAnnotOrNoop>>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub type_parameters: Option<TypeParamDeclOrNoop>, } impl From<FunctionExpression> for FunctionDeclaration { fn from(expr: FunctionExpression) -> Self { FunctionDeclaration { base: expr.base, id: expr.id, params: expr.params, body: expr.body, generator: expr.generator, is_async: expr.is_async, expression: false, return_type: expr.return_type, type_parameters: expr.type_parameters, } } } #[derive(Debug, Clone, PartialEq)] #[ast_serde("EnumBooleanMember")] pub struct EnumBooleanMember { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, pub init: BooleanLiteral, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("EnumNumberMember")] pub struct EnumNumberMember { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, pub init: NumericLiteral, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("EnumStringMember")] pub struct EnumStringMember { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, pub init: StringLiteral, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum EnumStringBodyMember { #[tag("EnumStringBodyMember")] String(EnumStringMember), #[tag("EnumDefaultedMember")] Defaulted(EnumDefaultedMember), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("EnumDefaultedMember")] pub struct EnumDefaultedMember { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum EnumMember { #[tag("EnumBooleanMember")] Boolean(EnumBooleanMember), #[tag("EnumNumberMember")] Number(EnumNumberMember), #[tag("EnumStringMember")] String(EnumStringMember), #[tag("EnumDefaultedMember")] Defaulted(EnumDefaultedMember), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("EnumBooleanBody")] pub struct EnumBooleanBody { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub members: Vec<EnumBooleanMember>, #[serde(default)] pub explicit_type: bool, #[serde(default)] pub has_unknown_members: bool, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("EnumNumberBody")] pub struct EnumNumberBody { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub members: Vec<EnumNumberMember>, #[serde(default)] pub explicit_type: bool, #[serde(default)] pub has_unknown_members: bool, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("EnumStringBody")] pub struct EnumStringBody { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub members: Vec<EnumStringBodyMember>, #[serde(default)] pub explicit_type: bool, #[serde(default)] pub has_unknown_members: bool, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("EnumSymbolBody")] pub struct EnumSymbolBody { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub members: Vec<EnumDefaultedMember>, #[serde(default)] pub has_unknown_members: bool, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum EnumBody { #[tag("EnumBooleanBody")] Boolean(EnumBooleanBody), #[tag("EnumNumberBody")] Number(EnumNumberBody), #[tag("EnumStringBody")] String(EnumStringBody), #[tag("EnumSymbolBody")] Symbol(EnumSymbolBody), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("EnumDeclaration")] pub struct EnumDeclaration { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, pub body: EnumBody, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("EnumDeclaration")] pub struct UsingDeclaration { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub declarations: Vec<VariableDeclarator>, }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_ast/src/expr.rs
Rust
use serde::{Deserialize, Serialize}; use swc_atoms::Atom; use swc_common::ast_serde; use crate::{ class::{ClassBody, ClassImpl}, common::{ BaseNode, Decorator, Identifier, LVal, MetaProperty, Param, PrivateName, SpreadElement, SuperTypeParams, TypeAnnotOrNoop, TypeParamDeclOrNoop, }, flow::{ InterfaceExtends, TypeAnnotation, TypeParameterDeclaration, TypeParameterInstantiation, }, jsx::{JSXElement, JSXFragment, JSXNamespacedName}, lit::{Literal, TemplateLiteral}, module::{Import, Program}, object::{ObjectMethod, ObjectProperty}, stmt::{BlockStatement, ExpressionStatement}, typescript::{ TSAsExpression, TSNonNullExpression, TSTypeAssertion, TSTypeParameterInstantiation, }, }; #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Expression { #[tag("ArrayExpression")] Array(ArrayExpression), #[tag("AssignmentExpression")] Assignment(AssignmentExpression), #[tag("BinaryExpression")] Binary(BinaryExpression), #[tag("CallExpression")] Call(CallExpression), #[tag("ConditionalExpression")] Conditional(ConditionalExpression), #[tag("FunctionExpression")] Func(FunctionExpression), #[tag("Identifier")] Id(Identifier), #[tag("StringLiteral")] #[tag("NumericLiteral")] #[tag("NullLiteral")] #[tag("BooleanLiteral")] #[tag("RegExpLiteral")] #[tag("DecimalLiteral")] #[tag("BigIntLiteral")] Literal(Literal), #[tag("LogicalExpression")] Logical(LogicalExpression), #[tag("MemberExpression")] Member(MemberExpression), #[tag("NewExpression")] New(NewExpression), #[tag("ObjectExpression")] Object(ObjectExpression), #[tag("SequenceExpression")] Sequence(SequenceExpression), #[tag("ParenthesizedExpression")] Parenthesized(ParenthesizedExpression), #[tag("ThisExpression")] This(ThisExpression), #[tag("UnaryExpression")] Unary(UnaryExpression), #[tag("UpdateExpression")] Update(UpdateExpression), #[tag("ArrowFunctionExpression")] ArrowFunc(ArrowFunctionExpression), #[tag("ClassExpression")] Class(ClassExpression), #[tag("MetaProperty")] MetaProp(MetaProperty), #[tag("Super")] Super(Super), #[tag("TaggedTemplateExpression")] TaggedTemplate(TaggedTemplateExpression), #[tag("TemplateLiteral")] TemplateLiteral(TemplateLiteral), #[tag("YieldExpression")] Yield(YieldExpression), #[tag("AwaitExpression")] Await(AwaitExpression), #[tag("Import")] Import(Import), #[tag("OptionalMemberExpression")] OptionalMember(OptionalMemberExpression), #[tag("OptionalCallExpression")] OptionalCall(OptionalCallExpression), #[tag("TypeCastExpression")] TypeCast(TypeCastExpression), #[tag("JSXElement")] JSXElement(JSXElement), #[tag("Fragment")] JSXFragment(JSXFragment), #[tag("BindExpression")] Bind(BindExpression), #[tag("PipelinePrimaryTopicReference")] PipelinePrimaryTopicRef(PipelinePrimaryTopicReference), #[tag("DoExpression")] Do(DoExpression), #[tag("RecordExpression")] Record(RecordExpression), #[tag("TupleExpression")] Tuple(TupleExpression), #[tag("ModuleExpression")] Module(ModuleExpression), #[tag("TSAsExpression")] TSAs(TSAsExpression), #[tag("TSTypeAssertion")] TSTypeAssertion(TSTypeAssertion), #[tag("TSNonNullExpression")] TSNonNull(TSNonNullExpression), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ExpressionWrapper { #[tag("ExpressionStatement")] Stmt(ExpressionStatement), #[tag("ParenthesizedExpression")] Parenthesized(ParenthesizedExpression), #[tag("TypeCastExpression")] TypeCast(TypeCastExpression), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ArrayExprEl { #[tag("SpreadElement")] Spread(SpreadElement), #[tag("*")] Expr(Box<Expression>), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("ArrayExpression")] pub struct ArrayExpression { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub elements: Vec<Option<ArrayExprEl>>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("AssignmentExpression")] pub struct AssignmentExpression { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub operator: Atom, pub left: Box<LVal>, pub right: Box<Expression>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum MemberExprProp { #[tag("Identifier")] Id(Identifier), #[tag("PrivateName")] PrivateName(PrivateName), #[tag("*")] Expr(Box<Expression>), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("MemberExpression")] pub struct MemberExpression { #[serde(flatten)] pub base: BaseNode, pub object: Box<Expression>, pub property: Box<MemberExprProp>, #[serde(default)] pub computed: bool, #[serde(default, serialize_with = "crate::ser::serialize_optional")] pub optional: Option<bool>, } // Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub enum BinaryExprOp { #[serde(rename = "+")] Addition, #[serde(rename = "-")] Subtraction, #[serde(rename = "/")] Division, #[serde(rename = "%")] Remainder, #[serde(rename = "*")] Multiplication, #[serde(rename = "**")] Exponentiation, #[serde(rename = "&")] And, #[serde(rename = "|")] Or, #[serde(rename = ">>")] RightShift, #[serde(rename = ">>>")] UnsignedRightShift, #[serde(rename = "<<")] LeftShift, #[serde(rename = "^")] Xor, #[serde(rename = "==")] Equal, #[serde(rename = "===")] StrictEqual, #[serde(rename = "!=")] NotEqual, #[serde(rename = "!==")] StrictNotEqual, #[serde(rename = "in")] In, #[serde(rename = "instanceof")] Instanceof, #[serde(rename = ">")] GreaterThan, #[serde(rename = "<")] LessThan, #[serde(rename = ">=")] GreaterThanOrEqual, #[serde(rename = "<=")] LessThanOrEqual, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum BinaryExprLeft { #[tag("PrivateName")] Private(PrivateName), #[tag("*")] Expr(Box<Expression>), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("BinaryExpression")] pub struct BinaryExpression { #[serde(flatten)] pub base: BaseNode, pub operator: BinaryExprOp, pub left: Box<BinaryExprLeft>, pub right: Box<Expression>, } #[derive(Debug, Clone, PartialEq, Eq)] #[ast_serde("V8IntrinsicIdentifier")] pub struct V8IntrinsicIdentifier { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub name: Atom, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Callee { #[tag("V8IntrinsicIdentifier")] V8Id(V8IntrinsicIdentifier), #[tag("*")] Expr(Box<Expression>), } impl From<Expression> for Callee { fn from(expr: Expression) -> Self { Callee::Expr(Box::new(expr)) } } #[derive(Debug, Clone, PartialEq, Eq)] #[ast_serde("ArgumentPlaceholder")] pub struct ArgumentPlaceholder { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Arg { #[tag("SpreadElement")] Spread(SpreadElement), #[tag("JSXNamespacedName")] JSXName(JSXNamespacedName), #[tag("ArgumentPlaceholder")] Placeholder(ArgumentPlaceholder), #[tag("*")] Expr(Box<Expression>), } impl From<ArrayExprEl> for Arg { fn from(el: ArrayExprEl) -> Self { match el { ArrayExprEl::Expr(e) => Arg::Expr(e), ArrayExprEl::Spread(s) => Arg::Spread(s), } } } #[derive(Debug, Clone, PartialEq)] #[ast_serde("CallExpression")] pub struct CallExpression { #[serde(flatten)] pub base: BaseNode, pub callee: Box<Callee>, #[serde(default)] pub arguments: Vec<Arg>, #[serde(default, serialize_with = "crate::ser::serialize_optional")] pub optional: Option<bool>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub type_arguments: Option<TypeParameterInstantiation>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub type_parameters: Option<TSTypeParameterInstantiation>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("ConditionalExpression")] pub struct ConditionalExpression { #[serde(flatten)] pub base: BaseNode, pub test: Box<Expression>, pub consequent: Box<Expression>, pub alternate: Box<Expression>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("FunctionExpression")] pub struct FunctionExpression { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub id: Option<Identifier>, #[serde(default)] pub params: Vec<Param>, pub body: BlockStatement, #[serde(default)] pub generator: Option<bool>, #[serde(default, rename = "async")] pub is_async: Option<bool>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub return_type: Option<Box<TypeAnnotOrNoop>>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub type_parameters: Option<TypeParamDeclOrNoop>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("NewExpression")] pub struct NewExpression { #[serde(flatten)] pub base: BaseNode, pub callee: Callee, #[serde(default)] pub arguments: Vec<Arg>, #[serde( default, skip_serializing_if = "crate::flavor::Flavor::skip_none_and_false" )] pub optional: Option<bool>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub type_arguments: Option<TypeParameterInstantiation>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub type_parameters: Option<TSTypeParameterInstantiation>, } // Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub enum LogicalExprOp { #[serde(rename = "||")] Or, #[serde(rename = "&&")] And, #[serde(rename = "??")] Nullish, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("LogicalExpression")] pub struct LogicalExpression { #[serde(flatten)] pub base: BaseNode, pub operator: LogicalExprOp, pub left: Box<Expression>, pub right: Box<Expression>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ObjectExprProp { #[tag("ObjectMethod")] Method(ObjectMethod), #[tag("ObjectProperty")] Prop(ObjectProperty), #[tag("SpreadElement")] Spread(SpreadElement), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("ObjectExpression")] pub struct ObjectExpression { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub properties: Vec<ObjectExprProp>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("SequenceExpression")] pub struct SequenceExpression { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub expressions: Vec<Box<Expression>>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("ParenthesizedExpression")] pub struct ParenthesizedExpression { #[serde(flatten)] pub base: BaseNode, pub expression: Box<Expression>, } #[derive(Debug, Clone, PartialEq, Eq)] #[ast_serde("ThisExpression")] pub struct ThisExpression { #[serde(flatten)] pub base: BaseNode, } // Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum UnaryExprOp { Void, Throw, Delete, #[serde(rename = "!")] LogicalNot, #[serde(rename = "+")] Plus, #[serde(rename = "-")] Negation, #[serde(rename = "~")] BitwiseNot, Typeof, } fn default_prefix() -> bool { true } #[derive(Debug, Clone, PartialEq)] #[ast_serde("UnaryExpression")] pub struct UnaryExpression { #[serde(flatten)] pub base: BaseNode, pub operator: UnaryExprOp, pub argument: Box<Expression>, #[serde(default = "default_prefix")] pub prefix: bool, } // Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub enum UpdateExprOp { #[serde(rename = "++")] Increment, #[serde(rename = "--")] Decrement, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("UpdateExpression")] pub struct UpdateExpression { #[serde(flatten)] pub base: BaseNode, pub operator: UpdateExprOp, pub argument: Box<Expression>, #[serde(default)] pub prefix: bool, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ArrowFuncExprBody { #[tag("BlockStatement")] Block(BlockStatement), #[tag("*")] Expr(Box<Expression>), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("ArrowFunctionExpression")] pub struct ArrowFunctionExpression { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub params: Vec<Param>, pub body: Box<ArrowFuncExprBody>, #[serde(default, rename = "async")] pub is_async: bool, #[serde(default)] pub expression: bool, #[serde(default)] pub generator: bool, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub return_type: Option<Box<TypeAnnotOrNoop>>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub type_parameters: Option<TypeParamDeclOrNoop>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("ClassExpression")] pub struct ClassExpression { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub id: Option<Identifier>, #[serde(default)] pub super_class: Option<Box<Expression>>, pub body: ClassBody, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_empty")] pub decorators: Option<Vec<Decorator>>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_empty")] pub implements: Option<Vec<ClassImpl>>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub mixins: Option<InterfaceExtends>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub super_type_parameters: Option<SuperTypeParams>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub type_parameters: Option<TypeParamDeclOrNoop>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum TaggedTemplateExprTypeParams { #[tag("TypeParameterDeclaration")] Flow(TypeParameterDeclaration), #[tag("TSTypeParameterInstantiation")] TS(TSTypeParameterInstantiation), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("TaggedTemplateExpression")] pub struct TaggedTemplateExpression { #[serde(flatten)] pub base: BaseNode, pub tag: Box<Expression>, pub quasi: TemplateLiteral, #[serde(default)] pub type_parameters: Option<TaggedTemplateExprTypeParams>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("YieldExpression")] pub struct YieldExpression { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub argument: Option<Box<Expression>>, #[serde(default)] pub delegate: bool, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("AwaitExpression")] pub struct AwaitExpression { #[serde(flatten)] pub base: BaseNode, pub argument: Box<Expression>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum OptionalMemberExprProp { #[tag("Identifier")] Id(Identifier), #[tag("*")] Expr(Box<Expression>), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("OptionalMemberExpression")] pub struct OptionalMemberExpression { #[serde(flatten)] pub base: BaseNode, pub object: Box<Expression>, pub property: OptionalMemberExprProp, #[serde(default)] pub computed: bool, #[serde(default)] pub optional: bool, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("OptionalCallExpression")] pub struct OptionalCallExpression { #[serde(flatten)] pub base: BaseNode, pub callee: Box<Expression>, #[serde(default)] pub arguments: Vec<Arg>, #[serde(default)] pub optional: bool, #[serde(default)] pub type_arguments: Option<TypeParameterInstantiation>, #[serde(default)] pub type_parameters: Option<TSTypeParameterInstantiation>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("TypeCastExpression")] pub struct TypeCastExpression { #[serde(flatten)] pub base: BaseNode, pub expression: Box<Expression>, pub type_annotation: TypeAnnotation, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("BindExpression")] pub struct BindExpression { #[serde(flatten)] pub base: BaseNode, pub object: Box<Expression>, pub callee: Box<Expression>, } #[derive(Debug, Clone, PartialEq, Eq)] #[ast_serde("PipelinePrimaryTopicReference")] pub struct PipelinePrimaryTopicReference { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("DoExpression")] pub struct DoExpression { #[serde(flatten)] pub base: BaseNode, pub body: BlockStatement, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum RecordExprProp { #[tag("ObjectProperty")] Prop(ObjectProperty), #[tag("SpreadElement")] Spread(SpreadElement), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("RecordExpression")] pub struct RecordExpression { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub properties: Vec<RecordExprProp>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum TupleExprEl { #[tag("SpreadElement")] Spread(SpreadElement), #[tag("*")] Expr(Box<Expression>), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("TupleExpression")] pub struct TupleExpression { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub elements: Vec<TupleExprEl>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("ModuleExpression")] pub struct ModuleExpression { #[serde(flatten)] pub base: BaseNode, pub body: Program, } #[derive(Debug, Clone, PartialEq, Eq)] #[ast_serde("Super")] pub struct Super { #[serde(flatten)] pub base: BaseNode, }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_ast/src/flavor.rs
Rust
better_scoped_tls::scoped_tls!(static FLAVOR: Flavor); #[repr(u8)] #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Default)] pub enum Flavor { #[default] Babel, Acorn { extra_comments: bool, }, } impl Flavor { pub fn with<F, Ret>(self, op: F) -> Ret where F: FnOnce() -> Ret, { FLAVOR.set(&self, op) } pub fn current() -> Self { if FLAVOR.is_set() { FLAVOR.with(|v| *v) } else { Flavor::default() } } pub fn emit_loc(&self) -> bool { true } pub(crate) fn skip_range(_: &Option<[u32; 2]>) -> bool { matches!(Self::current(), Flavor::Babel) } pub(crate) fn skip_empty<T>(v: &T) -> bool where T: IsEmpty, { matches!(Self::current(), Flavor::Acorn { .. }) && v.is_empty() } pub(crate) fn skip_none<T>(v: &Option<T>) -> bool { matches!(Self::current(), Flavor::Acorn { .. }) && v.is_none() } pub(crate) fn skip_none_and_false(v: &Option<bool>) -> bool { matches!(Self::current(), Flavor::Acorn { .. }) && matches!(v, None | Some(false)) } } pub(crate) trait IsEmpty { fn is_empty(&self) -> bool; } impl IsEmpty for String { fn is_empty(&self) -> bool { self.is_empty() } } impl<T> IsEmpty for Vec<T> { fn is_empty(&self) -> bool { self.is_empty() } } impl<T> IsEmpty for Option<T> where T: IsEmpty, { fn is_empty(&self) -> bool { match self { Some(v) => v.is_empty(), None => true, } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_ast/src/flow.rs
Rust
use serde::{Deserialize, Serialize}; use swc_atoms::Atom; use swc_common::ast_serde; use crate::{ common::{BaseNode, IdOrQualifiedId, IdOrString, Identifier}, expr::TypeCastExpression, lit::StringLiteral, module::{ExportKind, ExportNamespaceSpecifier, ExportSpecifier}, stmt::BlockStatement, }; #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Flow { #[tag("AnyTypeAnnotation")] AnyTypeAnnotation(AnyTypeAnnotation), #[tag("ArrayTypeAnnotation")] ArrayTypeAnnotation(ArrayTypeAnnotation), #[tag("BooleanTypeAnnotation")] BooleanTypeAnnotation(BooleanTypeAnnotation), #[tag("BooleanLiteralTypeAnnotation")] BooleanLiteralTypeAnnotation(BooleanLiteralTypeAnnotation), #[tag("NullLiteralTypeAnnotation")] NullLiteralTypeAnnotation(NullLiteralTypeAnnotation), #[tag("ClassImplements")] ClassImplements(ClassImplements), #[tag("DeclareClass")] DeclareClass(DeclareClass), #[tag("DeclareFunction")] DeclareFunction(DeclareFunction), #[tag("DeclareInterface")] DeclareInterface(DeclareInterface), #[tag("DeclareModule")] DeclareModule(DeclareModule), #[tag("DeclareModuleExports")] DeclareModuleExports(DeclareModuleExports), #[tag("DeclareTypeAlias")] DeclareTypeAlias(DeclareTypeAlias), #[tag("DeclareOpaqueType")] DeclareOpaqueType(DeclareOpaqueType), #[tag("DeclareVariable")] DeclareVariable(DeclareVariable), #[tag("DeclareExportDeclaration")] DeclareExportDeclaration(DeclareExportDeclaration), #[tag("DeclareExportAllDeclaration")] DeclareExportAllDeclaration(DeclareExportAllDeclaration), #[tag("DeclaredPredicate")] DeclaredPredicate(DeclaredPredicate), #[tag("ExistsTypeAnnotation")] ExistsTypeAnnotation(ExistsTypeAnnotation), #[tag("FunctionTypeAnnotation")] FunctionTypeAnnotation(FunctionTypeAnnotation), #[tag("FunctionTypeParam")] FunctionTypeParam(FunctionTypeParam), #[tag("GenericTypeAnnotation")] GenericTypeAnnotation(GenericTypeAnnotation), #[tag("InferredPredicate")] InferredPredicate(InferredPredicate), #[tag("InterfaceExtends")] InterfaceExtends(InterfaceExtends), #[tag("InterfaceDeclaration")] InterfaceDeclaration(InterfaceDeclaration), #[tag("InterfaceTypeAnnotation")] InterfaceTypeAnnotation(InterfaceTypeAnnotation), #[tag("IntersectionTypeAnnotation")] IntersectionTypeAnnotation(IntersectionTypeAnnotation), #[tag("MixedTypeAnnotation")] MixedTypeAnnotation(MixedTypeAnnotation), #[tag("EmptyTypeAnnotation")] EmptyTypeAnnotation(EmptyTypeAnnotation), #[tag("NullableTypeAnnotation")] NullableTypeAnnotation(NullableTypeAnnotation), #[tag("NumberLiteralTypeAnnotation")] NumberLiteralTypeAnnotation(NumberLiteralTypeAnnotation), #[tag("NumberTypeAnnotation")] NumberTypeAnnotation(NumberTypeAnnotation), #[tag("ObjectTypeAnnotation")] ObjectTypeAnnotation(ObjectTypeAnnotation), #[tag("ObjectTypeInternalSlot")] ObjectTypeInternalSlot(ObjectTypeInternalSlot), #[tag("ObjectTypeCallProperty")] ObjectTypeCallProperty(ObjectTypeCallProperty), #[tag("ObjectTypeIndexer")] ObjectTypeIndexer(ObjectTypeIndexer), #[tag("ObjectTypeProperty")] ObjectTypeProperty(ObjectTypeProperty), #[tag("ObjectTypeSpreadProperty")] ObjectTypeSpreadProperty(ObjectTypeSpreadProperty), #[tag("OpaqueType")] OpaqueType(OpaqueType), #[tag("QualifiedTypeIdentifier")] QualifiedTypeIdentifier(QualifiedTypeIdentifier), #[tag("StringLiteralTypeAnnotation")] StringLiteralTypeAnnotation(StringLiteralTypeAnnotation), #[tag("StringTypeAnnotation")] StringTypeAnnotation(StringTypeAnnotation), #[tag("SymbolTypeAnnotation")] SymbolTypeAnnotation(SymbolTypeAnnotation), #[tag("ThisTypeAnnotation")] ThisTypeAnnotation(ThisTypeAnnotation), #[tag("TupleTypeAnnotation")] TupleTypeAnnotation(TupleTypeAnnotation), #[tag("TypeofTypeAnnotation")] TypeofTypeAnnotation(TypeofTypeAnnotation), #[tag("TypeAlias")] TypeAlias(TypeAlias), #[tag("TypeAnnotation")] TypeAnnotation(TypeAnnotation), #[tag("TypeCastExpression")] TypeCastExpression(TypeCastExpression), #[tag("TypeParameter")] TypeParameter(TypeParameter), #[tag("TypeParameterDeclaration")] TypeParameterDeclaration(TypeParameterDeclaration), #[tag("TypeParameterInstantiation")] TypeParameterInstantiation(TypeParameterInstantiation), #[tag("UnionTypeAnnotation")] UnionTypeAnnotation(UnionTypeAnnotation), #[tag("Variance")] Variance(Variance), #[tag("VoidTypeAnnotation")] VoidTypeAnnotation(VoidTypeAnnotation), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum FlowType { #[tag("AnyTypeAnnotation")] Any(AnyTypeAnnotation), #[tag("ArrayTypeAnnotation")] Array(ArrayTypeAnnotation), #[tag("BooleanTypeAnnotation")] Boolean(BooleanTypeAnnotation), #[tag("BooleanLiteralTypeAnnotation")] BooleanLiteral(BooleanLiteralTypeAnnotation), #[tag("NullLiteralTypeAnnotation")] NullLiteral(NullLiteralTypeAnnotation), #[tag("ExistsTypeAnnotation")] Exists(ExistsTypeAnnotation), #[tag("FunctionTypeAnnotation")] Function(FunctionTypeAnnotation), #[tag("GenericTypeAnnotation")] Generic(GenericTypeAnnotation), #[tag("InterfaceTypeAnnotation")] Interface(InterfaceTypeAnnotation), #[tag("IntersectionTypeAnnotation")] Intersection(IntersectionTypeAnnotation), #[tag("MixedTypeAnnotation")] Mixed(MixedTypeAnnotation), #[tag("EmptyTypeAnnotation")] Empty(EmptyTypeAnnotation), #[tag("NullableTypeAnnotation")] Nullable(NullableTypeAnnotation), #[tag("NumberLiteralTypeAnnotation")] NumerLiteral(NumberLiteralTypeAnnotation), #[tag("NumberTypeAnnotation")] Number(NumberTypeAnnotation), #[tag("ObjectTypeAnnotation")] Object(ObjectTypeAnnotation), #[tag("StringLiteralTypeAnnotation")] StringLiteral(StringLiteralTypeAnnotation), #[tag("StringTypeAnnotation")] String(StringTypeAnnotation), #[tag("SymbolTypeAnnotation")] Symbol(SymbolTypeAnnotation), #[tag("ThisTypeAnnotation")] This(ThisTypeAnnotation), #[tag("TupleTypeAnnotation")] Tuple(TupleTypeAnnotation), #[tag("TypeofTypeAnnotation")] Typeof(TypeofTypeAnnotation), #[tag("UnionTypeAnnotation")] Union(UnionTypeAnnotation), #[tag("VoidTypeAnnotation")] Void(VoidTypeAnnotation), } #[derive(Debug, Clone, PartialEq, Eq)] #[ast_serde] pub enum FlowBaseAnnotation { #[tag("AnyTypeAnnotation")] Any(AnyTypeAnnotation), #[tag("BooleanTypeAnnotation")] Boolean(BooleanTypeAnnotation), #[tag("NullLiteralTypeAnnotation")] NullLiteral(NullLiteralTypeAnnotation), #[tag("MixedTypeAnnotation")] Mixed(MixedTypeAnnotation), #[tag("EmptyTypeAnnotation")] Empty(EmptyTypeAnnotation), #[tag("NumberTypeAnnotation")] Number(NumberTypeAnnotation), #[tag("StringTypeAnnotation")] String(StringTypeAnnotation), #[tag("SymbolTypeAnnotation")] Symbol(SymbolTypeAnnotation), #[tag("ThisTypeAnnotation")] This(ThisTypeAnnotation), #[tag("VoidTypeAnnotation")] Void(VoidTypeAnnotation), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum FlowDeclaration { #[tag("DeclareClass")] Class(DeclareClass), #[tag("DeclareFunction")] Func(DeclareFunction), #[tag("DeclareInterface")] Interface(DeclareInterface), #[tag("DeclareModule")] Module(DeclareModule), #[tag("DeclareModuleExports")] ModuleExports(DeclareModuleExports), #[tag("DeclareTypeAlias")] DeclareTypeAlias(DeclareTypeAlias), #[tag("DeclareOpaqueType")] DeclareOpaqueType(DeclareOpaqueType), #[tag("DeclareVariable")] Var(DeclareVariable), #[tag("DeclareExportDeclaration")] ExportDecl(DeclareExportDeclaration), #[tag("DeclareExportAllDeclaration")] ExportAllDecl(DeclareExportAllDeclaration), #[tag("InterfaceDeclaration")] InterfaceDeclaration(InterfaceDeclaration), #[tag("OpaqueType")] OpaqueType(OpaqueType), #[tag("TypeAlias")] TypeAlias(TypeAlias), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum FlowPredicate { #[tag("DeclaredPredicate")] DeclaredPredicate(DeclaredPredicate), #[tag("InferredPredicate")] InferredPredicate(InferredPredicate), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TypeAnnotation { #[serde(flatten)] pub base: BaseNode, pub type_annotation: FlowType, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct AnyTypeAnnotation { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct ArrayTypeAnnotation { #[serde(flatten)] pub base: BaseNode, pub element_type: Box<FlowType>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct BooleanTypeAnnotation { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct BooleanLiteralTypeAnnotation { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub value: bool, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct NullLiteralTypeAnnotation { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct ExistsTypeAnnotation { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct FunctionTypeParam { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub name: Option<Identifier>, pub type_annotation: Box<FlowType>, #[serde(default)] pub optional: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct FunctionTypeAnnotation { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub type_parameters: Option<TypeParameterDeclaration>, #[serde(default)] pub params: Vec<FunctionTypeParam>, #[serde(default)] pub rest: Option<Box<FunctionTypeParam>>, pub return_type: Box<FlowType>, #[serde(default)] pub optional: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TypeParameterDeclaration { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub params: Vec<TypeParameter>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum PlusOrMinus { Plus, Minus, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct Variance { #[serde(flatten)] pub base: BaseNode, pub kind: PlusOrMinus, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TypeParameter { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub bound: Option<TypeAnnotation>, #[serde(default)] pub default: Option<FlowType>, #[serde(default)] pub variance: Option<Variance>, #[serde(default)] pub name: Atom, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TypeParameterInstantiation { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub params: Vec<FlowType>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct GenericTypeAnnotation { #[serde(flatten)] pub base: BaseNode, pub id: IdOrQualifiedId, #[serde(default)] pub type_parameters: Option<TypeParameterInstantiation>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct InterfaceExtends { #[serde(flatten)] pub base: BaseNode, pub id: IdOrQualifiedId, #[serde(default)] pub type_parameters: Option<TypeParameterInstantiation>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum ObjectTypePropKind { Init, Get, Set, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ObjectTypeProperty { #[serde(flatten)] pub base: BaseNode, pub key: IdOrString, pub value: FlowType, #[serde(default)] pub variance: Option<Variance>, pub kind: ObjectTypePropKind, #[serde(default)] pub method: bool, #[serde(default)] pub optional: bool, #[serde(default)] pub proto: bool, #[serde(default, rename = "static")] pub is_static: bool, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ObjectTypeSpreadProperty { #[serde(flatten)] pub base: BaseNode, pub argument: FlowType, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ObjectTypeAnnotProp { #[tag("ObjectTypeProperty")] Prop(ObjectTypeProperty), #[tag("ObjectTypeSpreadProperty")] Spread(ObjectTypeSpreadProperty), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ObjectTypeIndexer { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub id: Option<Identifier>, pub key: FlowType, pub value: FlowType, #[serde(default)] pub variance: Option<Variance>, #[serde(default, rename = "static")] pub is_static: bool, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ObjectTypeCallProperty { #[serde(flatten)] pub base: BaseNode, pub value: FlowType, #[serde(rename = "static")] pub is_static: bool, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ObjectTypeInternalSlot { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, pub value: FlowType, #[serde(default)] pub optional: bool, #[serde(default, rename = "static")] pub is_static: bool, #[serde(default)] pub method: bool, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct ObjectTypeAnnotation { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub properties: Vec<ObjectTypeAnnotProp>, #[serde(default)] pub indexers: Option<Vec<ObjectTypeIndexer>>, #[serde(default)] pub call_properties: Option<Vec<ObjectTypeCallProperty>>, #[serde(default)] pub internal_slots: Option<Vec<ObjectTypeInternalSlot>>, #[serde(default)] pub exact: bool, #[serde(default)] pub inexact: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct InterfaceTypeAnnotation { #[serde(flatten)] pub base: BaseNode, #[serde(flatten)] pub extends: Option<Vec<InterfaceExtends>>, pub body: ObjectTypeAnnotation, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct IntersectionTypeAnnotation { #[serde(flatten)] pub base: BaseNode, #[serde(flatten)] pub types: Vec<FlowType>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct MixedTypeAnnotation { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct EmptyTypeAnnotation { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct NullableTypeAnnotation { #[serde(flatten)] pub base: BaseNode, pub type_annotation: Box<FlowType>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct NumberLiteralTypeAnnotation { #[serde(flatten)] pub base: BaseNode, pub value: f64, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct NumberTypeAnnotation { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct StringLiteralTypeAnnotation { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub value: Atom, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct StringTypeAnnotation { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct SymbolTypeAnnotation { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct ThisTypeAnnotation { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TupleTypeAnnotation { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub types: Vec<FlowType>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TypeofTypeAnnotation { #[serde(flatten)] pub base: BaseNode, pub argument: Box<FlowType>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct UnionTypeAnnotation { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub types: Vec<FlowType>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct VoidTypeAnnotation { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct OpaqueType { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, #[serde(default)] pub type_parameters: Option<TypeParameterDeclaration>, #[serde(default)] pub supertype: Option<FlowType>, pub impltype: FlowType, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct DeclareOpaqueType { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, #[serde(default)] pub type_parameters: Option<TypeParameterDeclaration>, #[serde(default)] pub supertype: Option<FlowType>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TypeAlias { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, #[serde(default)] pub type_parameters: Option<TypeParameterDeclaration>, pub right: FlowType, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct ClassImplements { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, #[serde(default)] pub type_parameters: Option<TypeParameterInstantiation>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct DeclareClass { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub type_parameters: Option<TypeParameterInstantiation>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_empty")] pub extends: Option<Vec<InterfaceExtends>>, pub body: ObjectTypeAnnotation, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_empty")] pub implements: Option<Vec<ClassImplements>>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub mixins: Option<Vec<InterfaceExtends>>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct DeclareFunction { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, #[serde(default)] pub predicate: Option<Box<DeclaredPredicate>>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct DeclareInterface { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, #[serde(default)] pub type_parameters: Option<TypeParameterInstantiation>, #[serde(default)] pub extends: Option<Vec<InterfaceExtends>>, pub body: ObjectTypeAnnotation, #[serde(default)] pub implements: Option<Vec<ClassImplements>>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_empty")] pub mixins: Option<Vec<InterfaceExtends>>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub enum ModuleKind { #[serde(rename = "CommonJS")] CommonJs, #[serde(rename = "ES")] Es, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct DeclareModule { #[serde(flatten)] pub base: BaseNode, pub id: IdOrString, pub body: BlockStatement, #[serde(default)] pub kind: Option<ModuleKind>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct DeclareModuleExports { #[serde(flatten)] pub base: BaseNode, pub type_annotation: TypeAnnotation, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct DeclareTypeAlias { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, #[serde(default)] pub type_parameters: Option<TypeParameterDeclaration>, pub right: FlowType, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct DeclareVariable { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum DeclareExportDeclSpecifier { #[tag("ExportSpecifier")] Export(ExportSpecifier), #[tag("ExportNamespaceSpecifier")] Namespace(ExportNamespaceSpecifier), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct DeclareExportDeclaration { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub declaration: Option<Box<Flow>>, #[serde(default)] pub specifiers: Option<Vec<DeclareExportDeclSpecifier>>, #[serde(default)] pub source: Option<StringLiteral>, #[serde(default)] pub default: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct DeclareExportAllDeclaration { #[serde(flatten)] pub base: BaseNode, pub source: StringLiteral, #[serde(default)] pub export_kind: Option<ExportKind>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct DeclaredPredicate { #[serde(flatten)] pub base: BaseNode, pub value: Box<Flow>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct InferredPredicate { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct InterfaceDeclaration { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, #[serde(default)] pub type_parameters: Option<TypeParameterDeclaration>, #[serde(default)] pub extends: Option<Vec<InterfaceExtends>>, pub body: ObjectTypeAnnotation, #[serde(default)] pub implements: Option<Vec<ClassImplements>>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_empty")] pub mixins: Option<Vec<InterfaceExtends>>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct QualifiedTypeIdentifier { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, pub qualification: Box<IdOrQualifiedId>, }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_ast/src/jsx.rs
Rust
use swc_atoms::Atom; use swc_common::ast_serde; use crate::{ common::{BaseNode, Identifier, SuperTypeParams}, expr::Expression, lit::StringLiteral, }; #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum JSX { #[tag("JSXAttribute")] Attr(JSXAttribute), #[tag("JSXClosingElement")] ClosingEl(JSXClosingElement), #[tag("JSXElement")] El(JSXElement), #[tag("JSXEmptyExpression")] EmptyExpr(JSXEmptyExpression), #[tag("JSXExpressionContainer")] ExprContainer(JSXExpressionContainer), #[tag("JSXSpreadChild")] SpreadChild(JSXSpreadChild), #[tag("JSXIdentifier")] Id(JSXIdentifier), #[tag("JSXMemberExpression")] MemberExpr(JSXMemberExpression), #[tag("JSXNamespacedName")] NamespacedName(JSXNamespacedName), #[tag("JSXOpeningElement")] OpeningEl(JSXOpeningElement), #[tag("JSXSpreadAttribute")] SpreadAttr(JSXSpreadAttribute), #[tag("JSXText")] Text(JSXText), #[tag("JSXFragment")] Fragment(JSXFragment), #[tag("JSXOpeningFragment")] OpeningFragment(JSXOpeningFragment), #[tag("JSXClosingFragment")] ClosingFragment(JSXClosingFragment), } #[derive(Debug, Clone, PartialEq, Eq)] #[ast_serde] pub enum JSXAttrName { #[tag("JSXIdentifier")] Id(JSXIdentifier), #[tag("JSXNamespacedName")] Name(JSXNamespacedName), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum JSXAttrVal { #[tag("JSXElement")] Element(JSXElement), #[tag("JSXFragment")] Fragment(JSXFragment), #[tag("StringLiteral")] String(StringLiteral), #[tag("JSXExpressionContainer")] Expr(JSXExpressionContainer), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("JSXAttribute")] pub struct JSXAttribute { #[serde(flatten)] pub base: BaseNode, pub name: JSXAttrName, #[serde(default)] pub value: Option<JSXAttrVal>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("JSXClosingElement")] pub struct JSXClosingElement { #[serde(flatten)] pub base: BaseNode, pub name: JSXElementName, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("JSXElement")] pub struct JSXElement { #[serde(flatten)] pub base: BaseNode, pub opening_element: JSXOpeningElement, #[serde(default)] pub closing_element: Option<JSXClosingElement>, #[serde(default)] pub children: Vec<JSXElementChild>, #[serde(default)] pub self_closing: Option<bool>, } #[derive(Debug, Clone, PartialEq, Eq)] #[ast_serde("JSXEmptyExpression")] pub struct JSXEmptyExpression { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum JSXExprContainerExpr { #[tag("JSXEmptyExpression")] Empty(JSXEmptyExpression), #[tag("*")] Expr(Box<Expression>), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("JSXExpressionContainer")] pub struct JSXExpressionContainer { #[serde(flatten)] pub base: BaseNode, pub expression: JSXExprContainerExpr, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("JSXSpreadChild")] pub struct JSXSpreadChild { #[serde(flatten)] pub base: BaseNode, pub expression: Box<Expression>, } #[derive(Debug, Clone, PartialEq, Eq)] #[ast_serde("JSXIdentifier")] pub struct JSXIdentifier { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub name: Atom, } impl From<Identifier> for JSXIdentifier { fn from(id: Identifier) -> Self { JSXIdentifier { base: id.base, name: id.name, } } } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum JSXMemberExprObject { #[tag("JSXMemberExpression")] Expr(JSXMemberExpression), #[tag("JSXIdentifier")] Id(JSXIdentifier), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("JSXMemberExpression")] pub struct JSXMemberExpression { #[serde(flatten)] pub base: BaseNode, pub object: Box<JSXMemberExprObject>, pub property: JSXIdentifier, } #[derive(Debug, Clone, PartialEq, Eq)] #[ast_serde("JSXNamespacedName")] pub struct JSXNamespacedName { #[serde(flatten)] pub base: BaseNode, pub namespace: JSXIdentifier, pub name: JSXIdentifier, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum JSXOpeningElAttr { #[tag("JSXAttribute")] Attr(JSXAttribute), #[tag("JSXSpreadAttribute")] Spread(JSXSpreadAttribute), } #[derive(Debug, Clone, PartialEq)] #[ast_serde("JSXOpeningElement")] pub struct JSXOpeningElement { #[serde(flatten)] pub base: BaseNode, pub name: JSXElementName, #[serde(default)] pub attributes: Vec<JSXOpeningElAttr>, #[serde(default)] pub self_closing: bool, #[serde(default)] pub type_parameters: Option<SuperTypeParams>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("JSXSpreadAttribute")] pub struct JSXSpreadAttribute { #[serde(flatten)] pub base: BaseNode, pub argument: Box<Expression>, } // impl From<SpreadElement> for JSXSpreadAttribute { // fn from(spread: SpreadElement) -> Self { // JSXSpreadAttribute { // // base: spread.base.clone(), // base: spread.base, // argument: spread.argument, // } // } // } #[derive(Debug, Clone, PartialEq, Eq)] #[ast_serde("JSXText")] pub struct JSXText { #[serde(flatten)] pub base: BaseNode, pub value: Atom, } #[derive(Debug, Clone, PartialEq)] #[ast_serde("JSXFragment")] pub struct JSXFragment { #[serde(flatten)] pub base: BaseNode, pub opening_fragment: JSXOpeningFragment, pub closing_fragment: JSXClosingFragment, #[serde(default)] pub children: Vec<JSXElementChild>, } #[derive(Debug, Clone, PartialEq, Eq)] #[ast_serde("JSXOpeningFragment")] pub struct JSXOpeningFragment { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, PartialEq, Eq)] #[ast_serde("JSXClosingElement")] pub struct JSXClosingFragment { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum JSXElementName { #[tag("JSXIdentifier")] Id(JSXIdentifier), #[tag("JSXMemberExpression")] Expr(JSXMemberExpression), #[tag("JSXNamespacedName")] Name(JSXNamespacedName), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum JSXElementChild { #[tag("JSXText")] Text(JSXText), #[tag("JSXExpressionContainer")] Expr(JSXExpressionContainer), #[tag("JSXSpreadChild")] Spread(JSXSpreadChild), #[tag("JSXElement")] Element(JSXElement), #[tag("JSXFragment")] Fragment(JSXFragment), }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_ast/src/lib.rs
Rust
#![deny(clippy::all)] #![allow(clippy::enum_variant_names)] #![allow(clippy::large_enum_variant)] pub use class::*; pub use comment::*; pub use common::*; pub use decl::*; pub use expr::*; pub use flow::*; pub use jsx::*; pub use lit::*; pub use module::*; pub use object::*; pub use pat::*; pub use stmt::*; pub use typescript::*; mod class; mod comment; mod common; mod decl; mod expr; pub mod flavor; mod flow; mod jsx; mod lit; mod module; mod object; mod pat; mod ser; mod stmt; mod typescript;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_ast/src/lit.rs
Rust
use std::borrow::Cow; use serde::{ser::SerializeMap, Deserialize, Serialize}; use swc_atoms::Atom; use swc_common::ast_serde; use crate::{common::BaseNode, expr::Expression, flavor::Flavor, typescript::TSType}; #[derive(Debug, Clone, PartialEq)] pub enum Literal { String(StringLiteral), Numeric(NumericLiteral), Null(NullLiteral), Boolean(BooleanLiteral), RegExp(RegExpLiteral), Template(TemplateLiteral), BigInt(BigIntLiteral), Decimal(DecimalLiteral), } #[derive(Serialize)] struct AcornRegex<'a> { flags: &'a str, pattern: &'a str, } #[derive(Serialize)] struct Empty {} impl Serialize for Literal { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { match Flavor::current() { Flavor::Babel => { let b = match self { Literal::String(l) => BabelLiteral::String(l.clone()), Literal::Numeric(l) => BabelLiteral::Numeric(l.clone()), Literal::Null(l) => BabelLiteral::Null(l.clone()), Literal::Boolean(l) => BabelLiteral::Boolean(l.clone()), Literal::RegExp(l) => BabelLiteral::RegExp(l.clone()), Literal::Template(l) => BabelLiteral::Template(l.clone()), Literal::BigInt(l) => BabelLiteral::BigInt(l.clone()), Literal::Decimal(l) => BabelLiteral::Decimal(l.clone()), }; BabelLiteral::serialize(&b, serializer) } Flavor::Acorn { .. } => { let (base, value, raw) = match self { Literal::String(l) => ( &l.base, AcornLiteralValue::String(l.value.clone()), Cow::Owned(l.raw.to_string()), ), Literal::Numeric(l) => ( &l.base, AcornLiteralValue::Numeric(l.value), Cow::Owned(l.value.to_string()), ), Literal::Null(l) => ( &l.base, AcornLiteralValue::Null(None), Cow::Borrowed("null"), ), Literal::Boolean(l) => ( &l.base, AcornLiteralValue::Boolean(l.value), if l.value { Cow::Borrowed("true") } else { Cow::Borrowed("false") }, ), Literal::RegExp(l) => { let mut s = serializer.serialize_map(None)?; { // TODO(kdy1): This is bad. l.base .serialize(serde::__private::ser::FlatMapSerializer(&mut s))?; } s.serialize_entry("type", "Literal")?; s.serialize_entry( "regex", &AcornRegex { flags: &l.flags, pattern: &l.pattern, }, )?; s.serialize_entry("value", &Empty {})?; return s.end(); } Literal::Template(..) => todo!(), Literal::BigInt(l) => ( &l.base, AcornLiteralValue::BigInt(l.value.clone()), Cow::Owned(l.value.to_string()), ), Literal::Decimal(l) => ( &l.base, AcornLiteralValue::Decimal(l.value.clone()), Cow::Owned(l.value.to_string()), ), }; let acorn = AcornLiteral { type_: "Literal", raw: &raw, base, value, }; AcornLiteral::serialize(&acorn, serializer) } } } } impl<'de> Deserialize<'de> for Literal { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { BabelLiteral::deserialize(deserializer).map(|b| match b { BabelLiteral::String(l) => Literal::String(l), BabelLiteral::Numeric(l) => Literal::Numeric(l), BabelLiteral::Null(l) => Literal::Null(l), BabelLiteral::Boolean(l) => Literal::Boolean(l), BabelLiteral::RegExp(l) => Literal::RegExp(l), BabelLiteral::Template(l) => Literal::Template(l), BabelLiteral::BigInt(l) => Literal::BigInt(l), BabelLiteral::Decimal(l) => Literal::Decimal(l), }) } } /// Used for serialization/deserialization #[ast_serde] enum BabelLiteral { #[tag("StringLiteral")] String(StringLiteral), #[tag("NumericLiteral")] Numeric(NumericLiteral), #[tag("NullLiteral")] Null(NullLiteral), #[tag("BooleanLiteral")] Boolean(BooleanLiteral), #[tag("RegExpLiteral")] RegExp(RegExpLiteral), #[tag("TemplateLiteral")] Template(TemplateLiteral), #[tag("BigIntLiteral")] BigInt(BigIntLiteral), #[tag("DecimalLiteral")] Decimal(DecimalLiteral), } #[derive(Serialize)] struct AcornLiteral<'a> { /// `Literal`. #[serde(rename = "type")] type_: &'a str, raw: &'a str, #[serde(flatten)] base: &'a BaseNode, value: AcornLiteralValue, } #[derive(Serialize)] #[serde(untagged)] enum AcornLiteralValue { String(Atom), Numeric(f64), Null(Option<()>), Boolean(bool), BigInt(String), Decimal(Atom), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct StringLiteral { #[serde(flatten)] pub base: BaseNode, pub value: Atom, pub raw: Atom, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct NumericLiteral { #[serde(flatten)] pub base: BaseNode, pub value: f64, } /// Deprecated. Use NumericLiteral instead. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct NumberLiteral { #[serde(flatten)] pub base: BaseNode, pub value: f64, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct NullLiteral { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct BooleanLiteral { #[serde(flatten)] pub base: BaseNode, pub value: bool, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct RegExpLiteral { #[serde(flatten)] pub base: BaseNode, pub pattern: Atom, #[serde(default)] pub flags: Atom, } /// Deprecated. Use RegExpLiteral instead. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct RegexLiteral { #[serde(flatten)] pub base: BaseNode, pub pattern: Atom, #[serde(default)] pub flags: Atom, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct TemplateElVal { #[serde(default)] pub raw: Atom, #[serde(default)] pub cooked: Option<Atom>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct TemplateElement { #[serde(flatten)] pub base: BaseNode, pub value: TemplateElVal, #[serde(default)] pub tail: bool, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum TemplateLiteralExpr { #[tag("TSAnyKeyword")] #[tag("TSBooleanKeyword")] #[tag("TSBigIntKeyword")] #[tag("TSIntrinsicKeyword")] #[tag("TSNeverKeyword")] #[tag("TSNullKeyword")] #[tag("TSNumberKeyword")] #[tag("TSObjectKeyword")] #[tag("TSStringKeyword")] #[tag("TSSymbolKeyword")] #[tag("TSUndefinedKeyword")] #[tag("TSUnknownKeyword")] #[tag("TSVoidKeyword")] #[tag("TSThisType")] #[tag("TSFunctionType")] #[tag("TSConstructorType")] #[tag("TSTypeReference")] #[tag("TSTypePredicate")] #[tag("TSTypeQuery")] #[tag("TSTypeLiteral")] #[tag("TSArrayType")] #[tag("TSTupleType")] #[tag("TSOptionalType")] #[tag("TSRestType")] #[tag("TSUnionType")] #[tag("TSIntersectionType")] #[tag("TSConditionalType")] #[tag("TSInferType")] #[tag("TSParenthesizedType")] #[tag("TSTypeOperator")] #[tag("TSIndexedAccessType")] #[tag("TSMappedType")] #[tag("TSLiteralType")] #[tag("TSExpressionWithTypeArguments")] #[tag("TSImportType")] TSType(TSType), #[tag("*")] Expr(Box<Expression>), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TemplateLiteral { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub quasis: Vec<TemplateElement>, #[serde(default)] pub expressions: Vec<TemplateLiteralExpr>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct BigIntLiteral { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub value: String, #[serde(default)] pub raw: Atom, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct DecimalLiteral { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub value: Atom, }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_ast/src/module.rs
Rust
use serde::{Deserialize, Serialize}; use serde_json::Value; use swc_atoms::Atom; use swc_common::ast_serde; use crate::{ class::ClassDeclaration, comment::Comment, common::{BaseNode, Directive, IdOrString, Identifier}, decl::{Declaration, FunctionDeclaration}, expr::Expression, lit::StringLiteral, stmt::Statement, typescript::TSDeclareFunction, }; #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ModuleDeclaration { #[tag("ExportAllDeclaration")] ExportAll(ExportAllDeclaration), #[tag("ExportDefaultDeclaration")] ExportDefault(ExportDefaultDeclaration), #[tag("ExportNamedDeclaration")] ExportNamed(ExportNamedDeclaration), #[tag("ImportDeclaration")] Import(ImportDeclaration), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ExportDeclaration { #[tag("ExportAllDeclaration")] ExportAll(ExportAllDeclaration), #[tag("ExportDefaultDeclaration")] ExportDefault(ExportDefaultDeclaration), #[tag("ExportNamedDeclaration")] ExportNamed(ExportNamedDeclaration), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ModuleSpecifier { #[tag("ExportSpecifier")] Export(ExportSpecifier), #[tag("ImportDefaultSpecifier")] ImportDefault(ImportDefaultSpecifier), #[tag("ImportNamespaceSpecifier")] ImportNamespace(ImportNamespaceSpecifier), #[tag("ImportSpecifier")] Import(ImportSpecifier), #[tag("ExportNamespaceSpecifier")] ExportNamespace(ExportNamespaceSpecifier), #[tag("ExportDefaultSpecifier")] ExportDefault(ExportDefaultSpecifier), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct File { #[serde(flatten)] pub base: BaseNode, pub program: Program, #[serde(default)] pub comments: Option<Vec<Comment>>, #[serde(default)] pub tokens: Option<Vec<Value>>, // TODO: is this the right way to model any? } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct InterpreterDirective { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub value: Atom, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum SrcType { Script, Module, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct Program { #[serde(flatten)] pub base: BaseNode, pub body: Vec<Statement>, #[serde(default, skip_serializing_if = "crate::ser::skip_comments_on_program")] pub comments: Vec<Comment>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_empty")] pub directives: Vec<Directive>, pub source_type: SrcType, #[serde(default, skip_serializing_if = "crate::ser::skip_interpreter")] pub interpreter: Option<InterpreterDirective>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_empty")] pub source_file: String, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum ExportKind { Type, Value, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct ExportSpecifier { #[serde(flatten)] pub base: BaseNode, pub local: ModuleExportNameType, pub exported: ModuleExportNameType, pub export_kind: ExportKind, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ExportDefaultSpecifier { #[serde(flatten)] pub base: BaseNode, pub exported: Identifier, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ExportNamespaceSpecifier { #[serde(flatten)] pub base: BaseNode, pub exported: ModuleExportNameType, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct ExportAllDeclaration { #[serde(flatten)] pub base: BaseNode, pub source: StringLiteral, #[serde(default)] pub with: Option<Vec<ImportAttribute>>, #[serde(default)] pub export_kind: Option<ExportKind>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ExportDefaultDeclType { #[tag("FunctionDeclaration")] Func(FunctionDeclaration), #[tag("TSDeclareFunction")] TSFunc(TSDeclareFunction), #[tag("ClassDeclaration")] Class(ClassDeclaration), #[tag("*")] Expr(Box<Expression>), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ExportDefaultDeclaration { #[serde(flatten)] pub base: BaseNode, pub declaration: ExportDefaultDeclType, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ExportSpecifierType { #[tag("ExportSpecifier")] Export(ExportSpecifier), #[tag("ExportDefaultSpecifier")] Default(ExportDefaultSpecifier), #[tag("ExportNamespaceSpecifier")] Namespace(ExportNamespaceSpecifier), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ExportNamedDeclaration { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub declaration: Option<Box<Declaration>>, #[serde(default)] pub specifiers: Vec<ExportSpecifierType>, #[serde(default)] pub source: Option<StringLiteral>, #[serde(default)] pub with: Option<Vec<ImportAttribute>>, #[serde(default)] pub export_kind: Option<ExportKind>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct Import { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ImportAttribute { #[serde(flatten)] pub base: BaseNode, pub key: IdOrString, pub value: StringLiteral, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct ImportSpecifier { #[serde(flatten)] pub base: BaseNode, pub local: Identifier, pub imported: ModuleExportNameType, #[serde(default)] pub import_kind: Option<ImportKind>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ImportDefaultSpecifier { #[serde(flatten)] pub base: BaseNode, pub local: Identifier, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ImportNamespaceSpecifier { #[serde(flatten)] pub base: BaseNode, pub local: Identifier, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ImportSpecifierType { #[tag("ImportSpecifier")] Import(ImportSpecifier), #[tag("ImportDefaultSpecifier")] Default(ImportDefaultSpecifier), #[tag("ImportNamespaceSpecifier")] Namespace(ImportNamespaceSpecifier), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum ImportKind { Type, Typeof, Value, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct ImportDeclaration { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub specifiers: Vec<ImportSpecifierType>, pub source: StringLiteral, #[serde(default)] pub with: Option<Vec<ImportAttribute>>, #[serde(default)] pub import_kind: Option<ImportKind>, pub phase: Option<ImportPhase>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ModuleExportNameType { #[tag("Identifier")] Ident(Identifier), #[tag("StringLiteral")] Str(StringLiteral), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum ImportPhase { Source, Defer, }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_ast/src/object.rs
Rust
use serde::{ser::SerializeMap, Deserialize, Serialize}; use swc_common::ast_serde; use crate::{ common::{ BaseNode, Decorator, Identifier, Param, PatternLike, TypeAnnotOrNoop, TypeParamDeclOrNoop, }, expr::Expression, flavor::Flavor, flow::{ ObjectTypeCallProperty, ObjectTypeIndexer, ObjectTypeInternalSlot, ObjectTypeProperty, ObjectTypeSpreadProperty, }, lit::{NumericLiteral, StringLiteral}, stmt::BlockStatement, }; #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum UserWhitespacable { #[tag("ObjectMethod")] ObjectMethod(ObjectMethod), #[tag("ObjectProperty")] ObjectProperty(ObjectProperty), #[tag("ObjectTypeInternalSlot")] ObjectTypeInternalSlot(ObjectTypeInternalSlot), #[tag("ObjectTypeCallProperty")] ObjectTypeCallProperty(ObjectTypeCallProperty), #[tag("ObjectTypeIndexer")] ObjectTypeIndexer(ObjectTypeIndexer), #[tag("ObjectTypeProperty")] ObjectTypeProperty(ObjectTypeProperty), #[tag("ObjectTypeSpreadProperty")] ObjectTypeSpreadProperty(ObjectTypeSpreadProperty), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ObjectMember { #[tag("ObjectMember")] Method(ObjectMethod), #[tag("ObjectProperty")] Prop(ObjectProperty), } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum ObjectMethodKind { Method, Get, Set, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ObjectKey { #[tag("Identifier")] Id(Identifier), #[tag("StringLiteral")] String(StringLiteral), #[tag("NumericLiteral")] Numeric(NumericLiteral), #[tag("*")] Expr(Box<Expression>), } #[derive(Debug, Clone, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct ObjectMethod { #[serde(flatten)] pub base: BaseNode, pub kind: ObjectMethodKind, pub key: ObjectKey, #[serde(default)] pub params: Vec<Param>, pub body: BlockStatement, #[serde(default)] pub computed: bool, #[serde(default)] pub generator: Option<bool>, #[serde(default, rename = "async")] pub is_async: Option<bool>, #[serde(default)] pub decorator: Option<Vec<Decorator>>, #[serde(default)] pub return_type: Option<Box<TypeAnnotOrNoop>>, #[serde(default)] pub type_parameters: Option<TypeParamDeclOrNoop>, } impl Serialize for ObjectMethod { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { match Flavor::current() { Flavor::Babel => { let actual = BabelObjectMethod { type_: "ObjectMethod", base: &self.base, key: &self.key, kind: self.kind, params: &self.params, body: &self.body, computed: self.computed, generator: self.generator, is_async: self.is_async, decorator: self.decorator.as_deref(), return_type: self.return_type.as_deref(), type_parameters: self.type_parameters.as_ref(), }; actual.serialize(serializer) } Flavor::Acorn { .. } => { let mut s = serializer.serialize_map(None)?; { // TODO(kdy1): This is bad. self.base .serialize(serde::__private::ser::FlatMapSerializer(&mut s))?; } s.serialize_entry("type", "Property")?; s.serialize_entry("kind", &self.kind)?; s.serialize_entry("method", &false)?; s.serialize_entry("shorthand", &false)?; s.serialize_entry("key", &self.key)?; s.serialize_entry("computed", &self.computed)?; s.serialize_entry( "value", &AcornObjectMethodValue { type_: "FunctionExpression", base: &self.base, body: &self.body, params: &self.params, generator: self.generator.unwrap_or(false), is_async: self.is_async.unwrap_or(false), }, )?; s.end() } } } } #[derive(Serialize)] struct AcornObjectMethodValue<'a> { /// `FunctionExpression` #[serde(rename = "type")] type_: &'static str, #[serde(flatten)] base: &'a BaseNode, body: &'a BlockStatement, params: &'a [Param], generator: bool, #[serde(rename = "async")] is_async: bool, } #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct BabelObjectMethod<'a> { #[serde(rename = "type")] type_: &'static str, #[serde(flatten)] pub base: &'a BaseNode, pub kind: ObjectMethodKind, pub key: &'a ObjectKey, #[serde(default)] pub params: &'a [Param], pub body: &'a BlockStatement, #[serde(default)] pub computed: bool, #[serde(default)] pub generator: Option<bool>, #[serde(default, rename = "async")] pub is_async: Option<bool>, #[serde(default)] pub decorator: Option<&'a [Decorator]>, #[serde(default)] pub return_type: Option<&'a TypeAnnotOrNoop>, #[serde(default)] pub type_parameters: Option<&'a TypeParamDeclOrNoop>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ObjectPropVal { #[tag("Identifier")] #[tag("RestElement")] #[tag("AssignmentPattern")] #[tag("ArrayPattern")] #[tag("ObjectPattern")] Pattern(PatternLike), #[tag("*")] Expr(Box<Expression>), } #[derive(Debug, Clone, Deserialize, PartialEq)] pub struct ObjectProperty { #[serde(flatten)] pub base: BaseNode, pub key: ObjectKey, pub value: ObjectPropVal, #[serde(default)] pub computed: bool, #[serde(default)] pub shorthand: bool, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub decorators: Option<Vec<Decorator>>, } #[derive(Serialize)] struct BabelObjectProperty<'a> { #[serde(rename = "type")] type_: &'a str, #[serde(flatten)] base: &'a BaseNode, key: &'a ObjectKey, value: &'a ObjectPropVal, method: bool, computed: bool, shorthand: bool, #[serde(skip_serializing_if = "crate::flavor::Flavor::skip_none")] decorators: Option<&'a [Decorator]>, } impl Serialize for ObjectProperty { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { match Flavor::current() { Flavor::Babel => { let actual = BabelObjectProperty { type_: "ObjectProperty", base: &self.base, key: &self.key, value: &self.value, method: false, computed: self.computed, shorthand: self.shorthand, decorators: self.decorators.as_deref(), }; actual.serialize(serializer) } Flavor::Acorn { .. } => { let mut s = serializer.serialize_map(None)?; { // TODO(kdy1): This is bad. self.base .serialize(serde::__private::ser::FlatMapSerializer(&mut s))?; } s.serialize_entry("type", "Property")?; s.serialize_entry("kind", "init")?; s.serialize_entry("method", &false)?; s.serialize_entry("shorthand", &self.shorthand)?; s.serialize_entry("key", &self.key)?; s.serialize_entry("value", &self.value)?; s.serialize_entry("computed", &self.computed)?; if let Some(decorators) = &self.decorators { if !decorators.is_empty() { s.serialize_entry("decorators", decorators)?; } } s.end() } } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_ast/src/pat.rs
Rust
use serde::{Deserialize, Serialize}; use swc_common::ast_serde; use crate::{ common::{BaseNode, Decorator, Identifier, PatternLike, RestElement, TypeAnnotOrNoop}, expr::{Expression, MemberExpression}, object::ObjectProperty, }; #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Pattern { #[tag("AssignmentPattern")] Assignment(AssignmentPattern), #[tag("ArrayPattern")] Array(ArrayPattern), #[tag("ObjectPattern")] Object(ObjectPattern), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ObjectPatternProp { #[tag("RestElement")] Rest(RestElement), #[tag("ObjectProperty")] Prop(ObjectProperty), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct ObjectPattern { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub properties: Vec<ObjectPatternProp>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_empty")] pub decorators: Option<Vec<Decorator>>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub type_annotation: Option<Box<TypeAnnotOrNoop>>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum AssignmentPatternLeft { #[tag("Identifier")] Id(Identifier), #[tag("ObjectPattern")] Object(ObjectPattern), #[tag("ArrayPattern")] Array(ArrayPattern), #[tag("MemberExpression")] Member(MemberExpression), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type", rename_all = "camelCase")] pub struct AssignmentPattern { #[serde(flatten)] pub base: BaseNode, pub left: AssignmentPatternLeft, pub right: Box<Expression>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_empty")] pub decorators: Option<Vec<Decorator>>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub type_annotation: Option<Box<TypeAnnotOrNoop>>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type", rename_all = "camelCase")] pub struct ArrayPattern { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub elements: Vec<Option<PatternLike>>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_empty")] pub decorators: Option<Vec<Decorator>>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_none")] pub type_annotation: Option<Box<TypeAnnotOrNoop>>, }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_ast/src/ser.rs
Rust
use serde::Serializer; use crate::flavor::Flavor; pub(crate) fn serialize_optional<S>(o: &Option<bool>, s: S) -> Result<S::Ok, S::Error> where S: Serializer, { s.serialize_some(&o.unwrap_or(false)) } /// Always serializes as a boolean value. pub(crate) fn serialize_as_bool<S>(o: &Option<bool>, s: S) -> Result<S::Ok, S::Error> where S: Serializer, { s.serialize_bool(o.unwrap_or(false)) } pub(crate) fn skip_expression_for_fn<T>(_: T) -> bool { match Flavor::current() { Flavor::Acorn { .. } => false, Flavor::Babel => true, } } pub(crate) fn skip_interpreter<T>(_: T) -> bool { match Flavor::current() { Flavor::Acorn { .. } => true, Flavor::Babel => false, } } pub(crate) fn skip_typescript<T>(_: T) -> bool { match Flavor::current() { Flavor::Acorn { .. } => true, Flavor::Babel => false, } } pub(crate) fn skip_comments_on_program<T>(_: T) -> bool { match Flavor::current() { Flavor::Acorn { extra_comments } => !extra_comments, _ => true, } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_ast/src/stmt.rs
Rust
use serde::{Deserialize, Serialize}; use swc_common::ast_serde; use crate::{ class::ClassDeclaration, common::{BaseNode, Directive, Identifier, LVal}, decl::{EnumDeclaration, FunctionDeclaration, VariableDeclaration}, expr::Expression, flow::{ DeclareClass, DeclareExportAllDeclaration, DeclareExportDeclaration, DeclareFunction, DeclareInterface, DeclareModule, DeclareModuleExports, DeclareOpaqueType, DeclareTypeAlias, DeclareVariable, InterfaceDeclaration, OpaqueType, TypeAlias, }, module::{ ExportAllDeclaration, ExportDefaultDeclaration, ExportNamedDeclaration, ImportDeclaration, }, pat::{ArrayPattern, ObjectPattern}, typescript::{ TSDeclareFunction, TSEnumDeclaration, TSExportAssignment, TSImportEqualsDeclaration, TSInterfaceDeclaration, TSModuleDeclaration, TSNamespaceExportDeclaration, TSTypeAliasDeclaration, }, UsingDeclaration, }; #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Statement { #[tag("BlockStatement")] Block(BlockStatement), #[tag("BreakStatement")] Break(BreakStatement), #[tag("ContinueStatement")] Continue(ContinueStatement), #[tag("DebuggerStatement")] Debugger(DebuggerStatement), #[tag("DoWhileStatement")] DoWhile(DoWhileStatement), #[tag("EmptyStatement")] Empty(EmptyStatement), #[tag("ExpressionStatement")] Expr(ExpressionStatement), #[tag("ForInStatement")] ForIn(ForInStatement), #[tag("ForStatement")] For(ForStatement), #[tag("FunctionDeclaration")] FuncDecl(FunctionDeclaration), #[tag("IfStatement")] If(IfStatement), #[tag("LabeledStatement")] Labeled(LabeledStatement), #[tag("ReturnStatement")] Return(ReturnStatement), #[tag("SwitchStatement")] Switch(SwitchStatement), #[tag("ThrowStatement")] Throw(ThrowStatement), #[tag("TryStatement")] Try(TryStatement), #[tag("VariableDeclaration")] VarDecl(VariableDeclaration), #[tag("WhileStatement")] While(WhileStatement), #[tag("WithStatement")] With(WithStatement), #[tag("ClassDeclaration")] ClassDecl(ClassDeclaration), #[tag("ExportAllDeclaration")] ExportAllDecl(ExportAllDeclaration), #[tag("ExportDefaultDeclaration")] ExportDefaultDecl(ExportDefaultDeclaration), #[tag("ExportNamedDeclaration")] ExportNamedDecl(ExportNamedDeclaration), #[tag("ForOfStatement")] ForOf(ForOfStatement), #[tag("ImportDeclaration")] ImportDecl(ImportDeclaration), #[tag("DeclareClass")] DeclClass(DeclareClass), #[tag("DeclareFunction")] DeclFunc(DeclareFunction), #[tag("DeclareInterface")] DeclInterface(DeclareInterface), #[tag("DeclareModule")] DeclModule(DeclareModule), #[tag("DeclareModuleExports")] DeclareModuleExports(DeclareModuleExports), #[tag("DeclareTypeAlias")] DeclTypeAlias(DeclareTypeAlias), #[tag("DeclareOpaqueType")] DeclOpaqueType(DeclareOpaqueType), #[tag("DeclareVariable")] DeclVar(DeclareVariable), #[tag("DeclareExportDeclaration")] DeclExportDeclaration(DeclareExportDeclaration), #[tag("DeclareExportAllDeclaration")] DeclExportAllDeclaration(DeclareExportAllDeclaration), #[tag("InterfaceDeclaration")] InterfaceDecl(InterfaceDeclaration), #[tag("OpaqueType")] OpaqueType(OpaqueType), #[tag("TypeAlias")] TypeAlias(TypeAlias), #[tag("EnumDeclaration")] EnumDecl(EnumDeclaration), #[tag("UsingDeclaration")] UsingDecl(UsingDeclaration), #[tag("TSDeclareFunction")] TSDeclFunc(TSDeclareFunction), #[tag("TSInterfaceDeclaration")] TSInterfaceDecl(TSInterfaceDeclaration), #[tag("TSTypeAliasDeclaration")] TSTypeAliasDecl(TSTypeAliasDeclaration), #[tag("TSEnumDeclaration")] TSEnumDecl(TSEnumDeclaration), #[tag("TSModuleDeclaration")] TSModuleDecl(TSModuleDeclaration), #[tag("TSImportEqualsDeclaration")] TSImportEqualsDecl(TSImportEqualsDeclaration), #[tag("TSExportAssignment")] TSExportAssignment(TSExportAssignment), #[tag("TSNamespaceExportDeclaration")] TSNamespaceExportDecl(TSNamespaceExportDeclaration), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum CompletionStatement { #[tag("BreakStatement")] Break(BreakStatement), #[tag("ContinueStatement")] Continue(ContinueStatement), #[tag("ReturnStatement")] Return(ReturnStatement), #[tag("ThrowStatement")] Throw(ThrowStatement), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum Loop { #[tag("DoWhileStatement")] DoWhile(DoWhileStatement), #[tag("ForInStatement")] ForIn(ForInStatement), #[tag("ForStatement")] For(ForStatement), #[tag("WhileStatement")] While(WhileStatement), #[tag("ForOfStatement")] ForOf(ForOfStatement), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum For { #[tag("ForInStatement")] InStmt(ForInStatement), #[tag("ForStatement")] Stmt(ForStatement), #[tag("ForOfStatement")] OfStmt(ForOfStatement), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ForXStatement { #[tag("ForInStatement")] ForIn(ForInStatement), #[tag("ForOfStatement")] ForOf(ForOfStatement), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum While { #[tag("DoWhileStatement")] DoWhile(DoWhileStatement), #[tag("WhileStatement")] While(WhileStatement), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct BlockStatement { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub body: Vec<Statement>, #[serde(default, skip_serializing_if = "crate::flavor::Flavor::skip_empty")] pub directives: Vec<Directive>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct BreakStatement { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub label: Option<Identifier>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ContinueStatement { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub label: Option<Identifier>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct DebuggerStatement { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct DoWhileStatement { #[serde(flatten)] pub base: BaseNode, pub test: Box<Expression>, pub body: Box<Statement>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct EmptyStatement { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ExpressionStatement { #[serde(flatten)] pub base: BaseNode, pub expression: Box<Expression>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ForStmtInit { #[tag("VariableDeclaration")] VarDecl(VariableDeclaration), #[tag("*")] Expr(Box<Expression>), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum ForStmtLeft { #[tag("VariableDeclaration")] VarDecl(VariableDeclaration), #[tag("*")] LVal(LVal), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ForInStatement { #[serde(flatten)] pub base: BaseNode, pub left: ForStmtLeft, pub right: Box<Expression>, pub body: Box<Statement>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ForStatement { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub init: Option<ForStmtInit>, #[serde(default)] pub test: Option<Box<Expression>>, #[serde(default)] pub update: Option<Box<Expression>>, pub body: Box<Statement>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ForOfStatement { #[serde(flatten)] pub base: BaseNode, pub left: ForStmtLeft, pub right: Box<Expression>, pub body: Box<Statement>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct IfStatement { #[serde(flatten)] pub base: BaseNode, pub test: Box<Expression>, pub consequent: Box<Statement>, #[serde(default)] pub alternate: Option<Box<Statement>>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct LabeledStatement { #[serde(flatten)] pub base: BaseNode, pub label: Identifier, pub body: Box<Statement>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ReturnStatement { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub argument: Option<Box<Expression>>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct SwitchCase { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub test: Option<Box<Expression>>, #[serde(default)] pub consequent: Vec<Statement>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct SwitchStatement { #[serde(flatten)] pub base: BaseNode, pub discriminant: Box<Expression>, #[serde(default)] pub cases: Vec<SwitchCase>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct ThrowStatement { #[serde(flatten)] pub base: BaseNode, pub argument: Box<Expression>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum CatchClauseParam { #[tag("Identifier")] Id(Identifier), #[tag("ArrayPattern")] Array(ArrayPattern), #[tag("ObjectPattern")] Object(ObjectPattern), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct CatchClause { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub param: Option<CatchClauseParam>, pub body: BlockStatement, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TryStatement { #[serde(flatten)] pub base: BaseNode, pub block: BlockStatement, #[serde(default)] pub handler: Option<CatchClause>, #[serde(default)] pub finalizer: Option<BlockStatement>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct WhileStatement { #[serde(flatten)] pub base: BaseNode, pub test: Box<Expression>, pub body: Box<Statement>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct WithStatement { #[serde(flatten)] pub base: BaseNode, pub object: Box<Expression>, pub body: Box<Statement>, }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_ast/src/typescript.rs
Rust
use serde::{Deserialize, Serialize}; use swc_atoms::Atom; use swc_common::ast_serde; use crate::{ class::ClassMethodKind, common::{Access, BaseNode, Decorator, IdOrRest, IdOrString, Identifier, Noop, Param}, expr::Expression, lit::{BigIntLiteral, BooleanLiteral, NumericLiteral, StringLiteral}, object::ObjectKey, pat::AssignmentPattern, stmt::Statement, }; #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum TSTypeElement { #[tag("TSCallSignatureDeclaration")] CallSignatureDecl(TSCallSignatureDeclaration), #[tag("TSConstructSignatureDeclaration")] ConstructSignatureDecl(TSConstructSignatureDeclaration), #[tag("TSPropertySignature")] PropSignature(TSPropertySignature), #[tag("TSMethodSignature")] MethodSignature(TSMethodSignature), #[tag("TSIndexSignature")] IndexSignature(TSIndexSignature), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum TSType { #[tag("TSAnyKeyword")] AnyKeyword(TSAnyKeyword), #[tag("TSBooleanKeyword")] BooleanKeyword(TSBooleanKeyword), #[tag("TSBigIntKeyword")] BigIntKeyword(TSBigIntKeyword), #[tag("TSIntrinsicKeyword")] IntrinsicKeyword(TSIntrinsicKeyword), #[tag("TSNeverKeyword")] NeverKeyword(TSNeverKeyword), #[tag("TSNullKeyword")] NullKeyword(TSNullKeyword), #[tag("TSNumberKeyword")] NumberKeyword(TSNumberKeyword), #[tag("TSObjectKeyword")] ObjectKeyword(TSObjectKeyword), #[tag("TSStringKeyword")] StringKeyword(TSStringKeyword), #[tag("TSSymbolKeyword")] SymbolKeyword(TSSymbolKeyword), #[tag("TSUndefinedKeyword")] UndefinedKeyword(TSUndefinedKeyword), #[tag("TSUnknownKeyword")] UnknownKeyword(TSUnknownKeyword), #[tag("TSVoidKeyword")] VoidKeyword(TSVoidKeyword), #[tag("TSThisType")] This(TSThisType), #[tag("TSFunctionType")] Function(TSFunctionType), #[tag("TSConstructorType")] Constructor(TSConstructorType), #[tag("TSTypeReference")] TypeRef(TSTypeReference), #[tag("TSTypePredicate")] TypePredicate(TSTypePredicate), #[tag("TSTypeQuery")] TypeQuery(TSTypeQuery), #[tag("TSTypeLiteral")] TypeLiteral(TSTypeLiteral), #[tag("TSArrayType")] Array(TSArrayType), #[tag("TSTupleType")] Tuple(TSTupleType), #[tag("TSOptionalType")] Optional(TSOptionalType), #[tag("TSRestType")] Rest(TSRestType), #[tag("TSUnionType")] Union(TSUnionType), #[tag("TSIntersectionType")] Intersection(TSIntersectionType), #[tag("TSConditionalType")] Conditional(TSConditionalType), #[tag("TSInferType")] Infer(TSInferType), #[tag("TSParenthesizedType")] Parenthesized(TSParenthesizedType), #[tag("TSTypeOperator")] TypeOp(TSTypeOperator), #[tag("TSIndexedAccessType")] IndexedAccess(TSIndexedAccessType), #[tag("TSMappedType")] Mapped(TSMappedType), #[tag("TSLiteralType")] Literal(TSLiteralType), #[tag("TSExpressionWithTypeArguments")] ExprWithArgs(TSExpressionWithTypeArguments), #[tag("TSImportType")] Import(TSImportType), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum TSBaseType { #[tag("TSAnyKeyword")] Any(TSAnyKeyword), #[tag("TSBooleanKeyword")] Boolean(TSBooleanKeyword), #[tag("TSBigIntKeyword")] BigInt(TSBigIntKeyword), #[tag("TSIntrinsicKeyword")] Intrinsic(TSIntrinsicKeyword), #[tag("TSNeverKeyword")] Never(TSNeverKeyword), #[tag("TSNullKeyword")] Null(TSNullKeyword), #[tag("TSNumberKeyword")] Number(TSNumberKeyword), #[tag("TSObjectKeyword")] Object(TSObjectKeyword), #[tag("TSStringKeyword")] String(TSStringKeyword), #[tag("TSSymbolKeyword")] Symbol(TSSymbolKeyword), #[tag("TSUndefinedKeyword")] Undefined(TSUndefinedKeyword), #[tag("TSUnknownKeyword")] Unknown(TSUnknownKeyword), #[tag("TSVoidKeyword")] Void(TSVoidKeyword), #[tag("TSThisType")] This(TSThisType), #[tag("TSLiteralType")] Literal(TSLiteralType), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSTypeAnnotation { #[serde(flatten)] pub base: BaseNode, pub type_annotation: TSType, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum TSParamPropParam { #[tag("Identifier")] Id(Identifier), #[tag("AssignmentPattern")] Assignment(AssignmentPattern), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TSParameterProperty { #[serde(flatten)] pub base: BaseNode, pub parameter: TSParamPropParam, #[serde(default)] pub accessibility: Option<Access>, #[serde(default)] pub readonly: Option<bool>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum TSFuncDeclTypeParams { #[tag("TSTypeParameterDeclaration")] Type(TSTypeParameterDeclaration), #[tag("Noop")] Noop(Noop), } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum TSFuncDeclTypeAnnot { #[tag("TSTypeAnnotation")] Type(Box<TSTypeAnnotation>), #[tag("Noop")] Noop(Noop), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSDeclareFunction { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub id: Option<Identifier>, #[serde(default)] pub type_parameters: Option<TSFuncDeclTypeParams>, #[serde(default)] pub params: Vec<Param>, #[serde(default)] pub return_type: Option<TSFuncDeclTypeAnnot>, #[serde(default, rename = "async")] pub is_async: Option<bool>, #[serde(default)] pub declare: Option<bool>, #[serde(default)] pub generator: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSDeclareMethod { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub decorators: Option<Vec<Decorator>>, pub key: ObjectKey, #[serde(default)] pub type_parameters: Option<TSFuncDeclTypeParams>, #[serde(default)] pub params: Vec<Param>, #[serde(default)] pub return_type: Option<TSFuncDeclTypeAnnot>, #[serde(default, rename = "abstract")] pub is_abstract: Option<bool>, #[serde(default)] pub access: Option<Access>, #[serde(default)] pub accessibility: Option<Access>, #[serde(default, rename = "async")] pub is_async: Option<bool>, #[serde(default)] pub computed: Option<bool>, #[serde(default)] pub generator: Option<bool>, #[serde(default)] pub kind: Option<ClassMethodKind>, #[serde(default)] pub optional: Option<bool>, #[serde(default, rename = "static")] pub is_static: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TSQualifiedName { #[serde(flatten)] pub base: BaseNode, pub left: Box<TSEntityName>, pub right: Identifier, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSCallSignatureDeclaration { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub type_parameters: Option<TSTypeParameterDeclaration>, #[serde(default)] pub parameters: Vec<IdOrRest>, #[serde(default)] pub type_annotation: Option<Box<TSTypeAnnotation>>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSConstructSignatureDeclaration { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub type_parameters: Option<TSTypeParameterDeclaration>, #[serde(default)] pub parameters: Vec<IdOrRest>, #[serde(default)] pub type_annotation: Option<Box<TSTypeAnnotation>>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSPropertySignature { #[serde(flatten)] pub base: BaseNode, pub key: Box<Expression>, #[serde(default)] pub type_annotation: Option<Box<TSTypeAnnotation>>, #[serde(default)] pub computed: Option<bool>, #[serde(default)] pub optional: Option<bool>, #[serde(default)] pub readonly: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSMethodSignature { #[serde(flatten)] pub base: BaseNode, pub key: Box<Expression>, #[serde(default)] pub type_parameters: Option<TSTypeParameterDeclaration>, #[serde(default)] pub parameters: Vec<IdOrRest>, #[serde(default)] pub type_annotation: Option<Box<TSTypeAnnotation>>, #[serde(default)] pub computed: Option<bool>, #[serde(default)] pub optional: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSIndexSignature { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub parameters: Vec<Identifier>, #[serde(default)] pub type_annotation: Option<Box<TSTypeAnnotation>>, #[serde(default)] pub readonly: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct TSAnyKeyword { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct TSBooleanKeyword { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct TSBigIntKeyword { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct TSIntrinsicKeyword { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct TSNeverKeyword { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct TSNullKeyword { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct TSNumberKeyword { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct TSObjectKeyword { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct TSStringKeyword { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct TSSymbolKeyword { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct TSUndefinedKeyword { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct TSUnknownKeyword { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct TSVoidKeyword { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct TSThisType { #[serde(flatten)] pub base: BaseNode, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TSFunctionType { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub type_parameters: Option<TSTypeParameterDeclaration>, #[serde(default)] pub parameters: Vec<IdOrRest>, #[serde(default)] pub type_annotation: Option<Box<TSTypeAnnotation>>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSConstructorType { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub type_parameters: Option<TSTypeParameterDeclaration>, #[serde(default)] pub parameters: Vec<IdOrRest>, #[serde(default)] pub type_annotation: Option<Box<TSTypeAnnotation>>, #[serde(default, rename = "abstract")] pub is_abstract: Option<bool>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum TSEntityName { #[tag("Identifier")] Id(Identifier), #[tag("TSQualifiedName")] Qualified(TSQualifiedName), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSTypeReference { #[serde(flatten)] pub base: BaseNode, pub type_name: TSEntityName, #[serde(default)] pub type_parameters: Option<TSTypeParameterInstantiation>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum TSTypePredicateParamName { #[tag("Identifier")] Id(Identifier), #[tag("TSThisType")] This(TSThisType), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSTypePredicate { #[serde(flatten)] pub base: BaseNode, pub parameter_name: TSTypePredicateParamName, #[serde(default)] pub type_annotation: Option<Box<TSTypeAnnotation>>, #[serde(default)] pub asserts: Option<bool>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum TSTypeQueryExprName { #[tag("Identifier")] #[tag("TSQualifiedName")] EntityName(TSEntityName), #[tag("TSImportType")] ImportType(TSImportType), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSTypeQuery { #[serde(flatten)] pub base: BaseNode, pub expr_name: TSTypeQueryExprName, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TSTypeLiteral { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub members: Vec<TSTypeElement>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSArrayType { #[serde(flatten)] pub base: BaseNode, pub element_type: Box<TSType>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum TSTupleTypeElType { #[tag("TSNamedTupleMember")] Member(TSNamedTupleMember), #[tag("*")] TSType(TSType), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSTupleType { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub element_types: Vec<TSTupleTypeElType>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSOptionalType { #[serde(flatten)] pub base: BaseNode, pub type_annotation: Box<TSType>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSRestType { #[serde(flatten)] pub base: BaseNode, pub type_annotation: Box<TSType>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSNamedTupleMember { #[serde(flatten)] pub base: BaseNode, pub label: Identifier, pub element_type: TSType, #[serde(default)] pub optional: bool, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TSUnionType { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub types: Vec<TSType>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TSIntersectionType { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub types: Vec<TSType>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSConditionalType { #[serde(flatten)] pub base: BaseNode, pub check_type: Box<TSType>, pub extends_type: Box<TSType>, pub true_type: Box<TSType>, pub false_type: Box<TSType>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSInferType { #[serde(flatten)] pub base: BaseNode, pub type_parameter: Box<TSTypeParameter>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSParenthesizedType { #[serde(flatten)] pub base: BaseNode, pub type_annotation: Box<TSType>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSTypeOperator { #[serde(flatten)] pub base: BaseNode, pub type_annotation: Box<TSType>, #[serde(default)] pub operator: Atom, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSIndexedAccessType { #[serde(flatten)] pub base: BaseNode, pub object_type: Box<TSType>, pub index_type: Box<TSType>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSMappedType { #[serde(flatten)] pub base: BaseNode, pub type_parameter: Box<TSTypeParameter>, #[serde(default)] pub type_annotation: Option<Box<TSType>>, #[serde(default)] pub name_type: Option<Box<TSType>>, #[serde(default)] pub optional: Option<bool>, #[serde(default)] pub readonly: Option<bool>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum TSLiteralTypeLiteral { #[tag("NumericLiteral")] Numeric(NumericLiteral), #[tag("StringLiteral")] String(StringLiteral), #[tag("BooleanLiteral")] Boolean(BooleanLiteral), #[tag("BigIntLiteral")] BigInt(BigIntLiteral), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TSLiteralType { #[serde(flatten)] pub base: BaseNode, pub literal: TSLiteralTypeLiteral, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSExpressionWithTypeArguments { #[serde(flatten)] pub base: BaseNode, pub expression: TSEntityName, #[serde(default)] pub type_parameters: Option<TSTypeParameterInstantiation>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSInterfaceDeclaration { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, #[serde(default)] pub type_parameters: Option<TSTypeParameterDeclaration>, #[serde(default)] pub extends: Option<TSExpressionWithTypeArguments>, pub body: TSInterfaceBody, #[serde(default)] pub declare: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TSInterfaceBody { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub body: Vec<TSTypeElement>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSTypeAliasDeclaration { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, #[serde(default)] pub type_parameters: Option<TSTypeParameterDeclaration>, pub type_annotation: TSType, #[serde(default)] pub declare: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSAsExpression { #[serde(flatten)] pub base: BaseNode, pub expression: Box<Expression>, pub type_annotation: TSType, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSTypeAssertion { #[serde(flatten)] pub base: BaseNode, pub type_annotation: TSType, pub expression: Box<Expression>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TSEnumDeclaration { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, #[serde(default)] pub members: Vec<TSEnumMember>, #[serde(default, rename = "const")] pub is_const: Option<bool>, #[serde(default)] pub declare: Option<bool>, #[serde(default)] pub initializer: Option<Box<Expression>>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TSEnumMember { #[serde(flatten)] pub base: BaseNode, pub id: IdOrString, #[serde(default)] pub initializer: Option<Box<Expression>>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum TSModuleDeclBody { #[tag("TSModuleBlock")] Block(TSModuleBlock), #[tag("TSModuleDeclaration")] Decl(TSModuleDeclaration), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TSModuleDeclaration { #[serde(flatten)] pub base: BaseNode, pub id: IdOrString, pub body: Box<TSModuleDeclBody>, #[serde(default)] pub declare: Option<bool>, #[serde(default)] pub global: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TSModuleBlock { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub body: Vec<Statement>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSImportType { #[serde(flatten)] pub base: BaseNode, pub argument: StringLiteral, #[serde(default)] pub qualifier: Option<TSEntityName>, #[serde(default)] pub type_parameters: Option<TSTypeParameterInstantiation>, } #[derive(Debug, Clone, PartialEq)] #[ast_serde] pub enum TSImportEqualsDeclModuleRef { #[tag("Identifier")] #[tag("TSQualifiedName")] Name(TSEntityName), #[tag("TSExternalModuleReference")] External(TSExternalModuleReference), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] pub struct TSImportEqualsDeclaration { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, pub module_reference: TSImportEqualsDeclModuleRef, #[serde(default)] pub is_export: bool, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type")] pub struct TSExternalModuleReference { #[serde(flatten)] pub base: BaseNode, pub expression: StringLiteral, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TSNonNullExpression { #[serde(flatten)] pub base: BaseNode, pub expression: Box<Expression>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TSExportAssignment { #[serde(flatten)] pub base: BaseNode, pub expression: Box<Expression>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TSNamespaceExportDeclaration { #[serde(flatten)] pub base: BaseNode, pub id: Identifier, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TSTypeParameterInstantiation { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub params: Vec<TSType>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TSTypeParameterDeclaration { #[serde(flatten)] pub base: BaseNode, pub params: Vec<TSTypeParameter>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "type")] pub struct TSTypeParameter { #[serde(flatten)] pub base: BaseNode, #[serde(default)] pub constraint: Option<Box<TSType>>, #[serde(default)] pub default: Option<Box<TSType>>, #[serde(default)] pub name: Atom, #[serde(default, rename = "in")] pub is_in: bool, #[serde(default, rename = "out")] pub is_out: bool, #[serde(default, rename = "const")] pub is_const: bool, }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/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_estree_compat/benches/babelify.rs
Rust
use std::{io::stderr, sync::Arc}; use codspeed_criterion_compat::{black_box, criterion_group, criterion_main, Bencher, Criterion}; use swc::config::IsModule; use swc_common::{ errors::Handler, FileName, FilePathMapping, Mark, SourceFile, SourceMap, GLOBALS, }; use swc_ecma_ast::{EsVersion, Program}; use swc_ecma_parser::Syntax; use swc_ecma_transforms::{compat::es2020, resolver, typescript}; use swc_estree_compat::babelify::{Babelify, Context}; static SOURCE: &str = include_str!("assets/AjaxObservable.ts"); fn mk() -> swc::Compiler { let cm = Arc::new(SourceMap::new(FilePathMapping::empty())); swc::Compiler::new(cm) } fn parse(c: &swc::Compiler, src: &str) -> (Arc<SourceFile>, Program) { let fm = c.cm.new_source_file( FileName::Real("rxjs/src/internal/observable/dom/AjaxObservable.ts".into()).into(), src.to_string(), ); let handler = Handler::with_emitter_writer(Box::new(stderr()), Some(c.cm.clone())); let comments = c.comments().clone(); let module = c .parse_js( fm.clone(), &handler, EsVersion::Es5, Syntax::Typescript(Default::default()), IsModule::Bool(true), Some(&comments), ) .unwrap(); (fm, module) } fn babelify_only(b: &mut Bencher) { GLOBALS.set(&Default::default(), || { let c = mk(); let (fm, module) = parse(&c, SOURCE); let handler = Handler::with_emitter_writer(Box::new(stderr()), Some(c.cm.clone())); let module = c.run_transform(&handler, false, || { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); module .apply(&mut resolver(unresolved_mark, top_level_mark, true)) .apply(&mut typescript::strip(unresolved_mark, top_level_mark)) .apply(&mut es2020(Default::default(), unresolved_mark)) }); b.iter(|| { let program = module.clone(); let ctx = Context { fm: fm.clone(), cm: c.cm.clone(), comments: c.comments().clone(), }; let babel_ast = program.babelify(&ctx); black_box(babel_ast) }); }) } fn parse_and_babelify(b: &mut Bencher, _name: &str, src: &str) { GLOBALS.set(&Default::default(), || { let c = mk(); b.iter(|| { let (fm, program) = parse(&c, src); let ctx = Context { fm, cm: c.cm.clone(), comments: c.comments().clone(), }; let babel_ast = program.babelify(&ctx); black_box(babel_ast); }); }) } fn bench_cases(c: &mut Criterion) { c.bench_function("babelify-only", babelify_only); /// https://esprima.org/test/compare.html macro_rules! src_to_babel_ast { ($name:ident, $src:expr) => { c.bench_function(stringify!($name), |b| { parse_and_babelify(b, stringify!($name), $src) }); }; } src_to_babel_ast!( parse_and_babelify_angular, include_str!("../../swc_ecma_parser/benches/files/angular-1.2.5.js") ); src_to_babel_ast!( parse_and_babelify_backbone, include_str!("../../swc_ecma_parser/benches/files/backbone-1.1.0.js") ); src_to_babel_ast!( parse_and_babelify_jquery, include_str!("../../swc_ecma_parser/benches/files/jquery-1.9.1.js") ); src_to_babel_ast!( parse_and_babelify_jquery_mobile, include_str!("../../swc_ecma_parser/benches/files/jquery.mobile-1.4.2.js") ); src_to_babel_ast!( parse_and_babelify_mootools, include_str!("../../swc_ecma_parser/benches/files/mootools-1.4.5.js") ); src_to_babel_ast!( parse_and_babelify_underscore, include_str!("../../swc_ecma_parser/benches/files/underscore-1.5.2.js") ); src_to_babel_ast!( parse_and_babelify_yui, include_str!("../../swc_ecma_parser/benches/files/yui-3.12.0.js") ); } criterion_group!(benches, bench_cases); criterion_main!(benches);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/scripts/test-acorn.js
JavaScript
// File to parse input as an AST using acorn const parserOptions = { ranges: true, locations: true, ecmaVersion: "latest", // https://github.com/tc39/proposal-hashbang allowHashBang: true, }; const acorn = require("acorn"); const res = acorn.parse(process.argv[1], parserOptions); console.log(JSON.stringify(res, void 0, 2));
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/scripts/update.sh
Shell
#!/usr/bin/env bash SCRIPT_DIR="`dirname "$0"`" IFS='' # maintain whitespace for filename in $SCRIPT_DIR/../src/ast/*.rs; do while read -r line; do [[ "$line" =~ ^[[:space:]]*$ ]] && continue [[ "$line" =~ ^[[:space:]]*# ]] && continue [[ "$line" =~ ^[[:space:]]*\/ ]] && continue echo "$line" done < "$filename" done
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/babelify/class.rs
Rust
use copyless::BoxHelper; use serde_json::value::Value; use swc_ecma_ast::{ Class, ClassMember, ClassMethod, ClassProp, Constructor, Decorator, MethodKind, PrivateMethod, PrivateProp, StaticBlock, }; use swc_estree_ast::{ ClassBody, ClassBodyEl, ClassExpression, ClassMethod as BabelClassMethod, ClassMethodKind, ClassPrivateMethod, ClassPrivateProperty, ClassProperty, Decorator as BabelDecorator, StaticBlock as BabelStaticBlock, }; use crate::babelify::{extract_class_body_span, Babelify, Context}; impl Babelify for Class { type Output = ClassExpression; fn babelify(self, ctx: &Context) -> Self::Output { let body = ClassBody { base: ctx.base(extract_class_body_span(&self, ctx)), body: self.body.babelify(ctx), }; ClassExpression { base: ctx.base(self.span), decorators: Some(self.decorators.babelify(ctx)), body, super_class: self .super_class .map(|expr| Box::alloc().init(expr.babelify(ctx).into())), type_parameters: self.type_params.map(|param| param.babelify(ctx).into()), super_type_parameters: self .super_type_params .map(|param| param.babelify(ctx).into()), implements: Some( self.implements .into_iter() .map(|imp| imp.babelify(ctx).into()) .collect(), ), id: Default::default(), mixins: Default::default(), } } } impl Babelify for ClassMember { type Output = ClassBodyEl; fn babelify(self, ctx: &Context) -> Self::Output { match self { ClassMember::Constructor(c) => ClassBodyEl::Method(c.babelify(ctx)), ClassMember::Method(m) => ClassBodyEl::Method(m.babelify(ctx)), ClassMember::PrivateMethod(m) => ClassBodyEl::PrivateMethod(m.babelify(ctx)), ClassMember::ClassProp(p) => ClassBodyEl::Prop(p.babelify(ctx)), ClassMember::PrivateProp(p) => ClassBodyEl::PrivateProp(p.babelify(ctx)), ClassMember::TsIndexSignature(s) => ClassBodyEl::TSIndex(s.babelify(ctx)), ClassMember::Empty(_) => panic!( "illegal conversion: Cannot convert {:?} to ClassBodyEl", &self ), ClassMember::StaticBlock(s) => ClassBodyEl::StaticBlock(s.babelify(ctx)), ClassMember::AutoAccessor(..) => todo!("auto accessor"), } } } impl Babelify for ClassProp { type Output = ClassProperty; fn babelify(self, ctx: &Context) -> Self::Output { let computed = Some(self.key.is_computed()); ClassProperty { base: ctx.base(self.span), key: self.key.babelify(ctx), value: self .value .map(|val| Box::alloc().init(val.babelify(ctx).into())), type_annotation: self .type_ann .map(|ann| Box::alloc().init(ann.babelify(ctx).into())), is_static: Some(self.is_static), decorators: Some(self.decorators.babelify(ctx)), computed, accessibility: self.accessibility.map(|access| access.babelify(ctx)), is_abstract: Some(self.is_abstract), optional: Some(self.is_optional), readonly: Some(self.readonly), declare: Some(self.declare), definite: Some(self.definite), } } } impl Babelify for PrivateProp { type Output = ClassPrivateProperty; fn babelify(self, ctx: &Context) -> Self::Output { ClassPrivateProperty { base: ctx.base(self.span), key: self.key.babelify(ctx), value: self .value .map(|expr| Box::alloc().init(expr.babelify(ctx).into())), type_annotation: self .type_ann .map(|ann| Box::alloc().init(ann.babelify(ctx).into())), static_any: Value::Bool(self.is_static), decorators: Some(self.decorators.babelify(ctx)), } } } impl Babelify for ClassMethod { type Output = BabelClassMethod; fn babelify(self, ctx: &Context) -> Self::Output { BabelClassMethod { base: ctx.base(self.span), key: self.key.babelify(ctx), kind: Some(self.kind.babelify(ctx)), is_static: Some(self.is_static), access: self.accessibility.map(|access| access.babelify(ctx)), accessibility: self.accessibility.map(|access| access.babelify(ctx)), is_abstract: Some(self.is_abstract), optional: Some(self.is_optional), params: self.function.params.babelify(ctx), body: self.function.body.unwrap().babelify(ctx), generator: Some(self.function.is_generator), is_async: Some(self.function.is_async), decorators: Some(self.function.decorators.babelify(ctx)), type_parameters: self.function.type_params.map(|t| t.babelify(ctx).into()), return_type: self .function .return_type .map(|t| Box::alloc().init(t.babelify(ctx).into())), computed: Default::default(), } } } impl Babelify for PrivateMethod { type Output = ClassPrivateMethod; fn babelify(self, ctx: &Context) -> Self::Output { ClassPrivateMethod { base: ctx.base(self.span), key: self.key.babelify(ctx), kind: Some(self.kind.babelify(ctx)), is_static: Some(self.is_static), access: self.accessibility.map(|access| access.babelify(ctx)), accessibility: self.accessibility.map(|access| access.babelify(ctx)), is_abstract: Some(self.is_abstract), optional: Some(self.is_optional), params: self.function.params.babelify(ctx), body: self.function.body.unwrap().babelify(ctx), generator: Some(self.function.is_generator), is_async: Some(self.function.is_async), decorators: Some(self.function.decorators.babelify(ctx)), type_parameters: self.function.type_params.map(|t| t.babelify(ctx).into()), return_type: self .function .return_type .map(|t| Box::alloc().init(t.babelify(ctx).into())), computed: Default::default(), } } } impl Babelify for Constructor { type Output = BabelClassMethod; fn babelify(self, ctx: &Context) -> Self::Output { BabelClassMethod { base: ctx.base(self.span), kind: Some(ClassMethodKind::Constructor), key: self.key.babelify(ctx), params: self.params.babelify(ctx), body: self.body.unwrap().babelify(ctx), access: self.accessibility.map(|access| access.babelify(ctx)), accessibility: self.accessibility.map(|access| access.babelify(ctx)), optional: Some(self.is_optional), computed: Default::default(), is_static: Default::default(), generator: Default::default(), is_async: Default::default(), is_abstract: Default::default(), decorators: Default::default(), return_type: Default::default(), type_parameters: Default::default(), } } } impl Babelify for Decorator { type Output = BabelDecorator; fn babelify(self, ctx: &Context) -> Self::Output { BabelDecorator { base: ctx.base(self.span), expression: Box::alloc().init(self.expr.babelify(ctx).into()), } } } impl Babelify for MethodKind { type Output = ClassMethodKind; fn babelify(self, _ctx: &Context) -> Self::Output { match self { MethodKind::Method => ClassMethodKind::Method, MethodKind::Getter => ClassMethodKind::Get, MethodKind::Setter => ClassMethodKind::Set, } } } impl Babelify for StaticBlock { type Output = BabelStaticBlock; fn babelify(self, ctx: &Context) -> Self::Output { BabelStaticBlock { base: ctx.base(self.span), body: self.body.stmts.babelify(ctx), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/babelify/decl.rs
Rust
use copyless::BoxHelper; use swc_ecma_ast::{ClassDecl, Decl, FnDecl, UsingDecl, VarDecl, VarDeclKind, VarDeclarator}; use swc_estree_ast::{ ClassBody, ClassDeclaration, Declaration, FunctionDeclaration, UsingDeclaration, VariableDeclaration, VariableDeclarationKind, VariableDeclarator, }; use crate::babelify::{extract_class_body_span, Babelify, Context}; impl Babelify for Decl { type Output = Declaration; fn babelify(self, ctx: &Context) -> Self::Output { match self { Decl::Class(d) => Declaration::ClassDecl(d.babelify(ctx)), Decl::Fn(d) => Declaration::FuncDecl(d.babelify(ctx)), Decl::Var(d) => Declaration::VarDecl(d.babelify(ctx)), Decl::Using(d) => Declaration::UsingDecl(d.babelify(ctx)), Decl::TsInterface(d) => Declaration::TSInterfaceDecl(d.babelify(ctx)), Decl::TsTypeAlias(d) => Declaration::TSTypeAliasDecl(d.babelify(ctx)), Decl::TsEnum(d) => Declaration::TSEnumDecl(d.babelify(ctx)), Decl::TsModule(d) => Declaration::TSModuleDecl(d.babelify(ctx)), } } } impl Babelify for FnDecl { type Output = FunctionDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { let func = self.function.babelify(ctx); FunctionDeclaration { base: func.base, id: Some(self.ident.babelify(ctx)), params: func.params, body: func.body, generator: func.generator, is_async: func.is_async, expression: false, return_type: func.return_type, type_parameters: func.type_parameters, } } } impl Babelify for ClassDecl { type Output = ClassDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { let is_abstract = self.class.is_abstract; // NOTE: The body field needs a bit of special handling because babel // represents the body as a node, whereas swc represents it as a vector of // statements. This means that swc does not have a span corresponding the // class body base node for babel. To solve this, we generate a new span // starting from the end of the identifier to the end of the body. // For example, // // babel ClassBody node starts here // v // class MyClass { // a = 0; // } // ^ // and ends here // // TODO: Verify that this implementation of class body span is correct. // It may need to be modified to take into account implements, super classes, // etc. let body_span = extract_class_body_span(&self.class, ctx); let class = self.class.babelify(ctx); ClassDeclaration { base: class.base, id: self.ident.babelify(ctx), super_class: class.super_class.map(|s| Box::alloc().init(*s)), body: ClassBody { base: ctx.base(body_span), ..class.body }, decorators: class.decorators, is_abstract: Some(is_abstract), declare: Some(self.declare), implements: class.implements, mixins: class.mixins, super_type_parameters: class.super_type_parameters, type_parameters: class.type_parameters, } } } impl Babelify for VarDecl { type Output = VariableDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { VariableDeclaration { base: ctx.base(self.span), kind: self.kind.babelify(ctx), declare: Some(self.declare), declarations: self.decls.babelify(ctx), } } } impl Babelify for VarDeclKind { type Output = VariableDeclarationKind; fn babelify(self, _ctx: &Context) -> Self::Output { match self { VarDeclKind::Var => VariableDeclarationKind::Var, VarDeclKind::Let => VariableDeclarationKind::Let, VarDeclKind::Const => VariableDeclarationKind::Const, } } } impl Babelify for VarDeclarator { type Output = VariableDeclarator; fn babelify(self, ctx: &Context) -> Self::Output { VariableDeclarator { base: ctx.base(self.span), id: self.name.babelify(ctx).into(), init: self.init.map(|i| Box::alloc().init(i.babelify(ctx).into())), definite: Some(self.definite), } } } impl Babelify for UsingDecl { type Output = UsingDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { UsingDeclaration { base: ctx.base(self.span), declarations: self.decls.babelify(ctx), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/babelify/expr.rs
Rust
use copyless::BoxHelper; use serde::{Deserialize, Serialize}; use swc_common::{BytePos, Span, Spanned}; use swc_ecma_ast::{ ArrayLit, ArrowExpr, AssignExpr, AssignTarget, AssignTargetPat, AwaitExpr, BinExpr, BinaryOp, BlockStmtOrExpr, CallExpr, Callee, ClassExpr, CondExpr, Expr, ExprOrSpread, FnExpr, Ident, Import, Lit, MemberExpr, MemberProp, MetaPropExpr, MetaPropKind, NewExpr, ObjectLit, ParenExpr, PropOrSpread, SeqExpr, SimpleAssignTarget, SpreadElement, Super, SuperProp, SuperPropExpr, TaggedTpl, ThisExpr, Tpl, TplElement, UnaryExpr, UpdateExpr, YieldExpr, }; use swc_estree_ast::{ flavor::Flavor, ArrayExprEl, ArrayExpression, ArrowFuncExprBody, ArrowFunctionExpression, AssignmentExpression, AwaitExpression, BinaryExprLeft, BinaryExpression, CallExpression, Callee as BabelCallee, ClassExpression, ConditionalExpression, Expression, FunctionExpression, Import as BabelImport, LVal, Literal, LogicalExpression, MemberExprProp, MemberExpression, MetaProperty, NewExpression, ObjectExprProp, ObjectExpression, ObjectKey, ObjectMember, ParenthesizedExpression, PrivateName, SequenceExpression, SpreadElement as BabelSpreadElement, Super as BabelSuper, TaggedTemplateExprTypeParams, TaggedTemplateExpression, TemplateElVal, TemplateElement, TemplateLiteral, TemplateLiteralExpr, ThisExpression, UnaryExpression, UpdateExpression, YieldExpression, }; use crate::babelify::{Babelify, Context}; #[derive(Debug, Clone, Serialize, Deserialize)] pub enum ExprOutput { Expr(Box<Expression>), Private(PrivateName), } impl Babelify for Expr { type Output = ExprOutput; fn babelify(self, ctx: &Context) -> Self::Output { match self { Expr::This(t) => ExprOutput::Expr(Box::alloc().init(Expression::This(t.babelify(ctx)))), Expr::Array(a) => { ExprOutput::Expr(Box::alloc().init(Expression::Array(a.babelify(ctx)))) } Expr::Object(o) => { ExprOutput::Expr(Box::alloc().init(Expression::Object(o.babelify(ctx)))) } Expr::Fn(f) => ExprOutput::Expr(Box::alloc().init(Expression::Func(f.babelify(ctx)))), Expr::Unary(u) => { ExprOutput::Expr(Box::alloc().init(Expression::Unary(u.babelify(ctx)))) } Expr::Update(u) => { ExprOutput::Expr(Box::alloc().init(Expression::Update(u.babelify(ctx)))) } Expr::Bin(b) => match b.babelify(ctx) { BinaryOrLogicalExpr::Binary(bin) => { ExprOutput::Expr(Box::alloc().init(Expression::Binary(bin))) } BinaryOrLogicalExpr::Logical(log) => { ExprOutput::Expr(Box::alloc().init(Expression::Logical(log))) } }, Expr::Assign(a) => { ExprOutput::Expr(Box::alloc().init(Expression::Assignment(a.babelify(ctx)))) } Expr::Member(m) => { ExprOutput::Expr(Box::alloc().init(Expression::Member(m.babelify(ctx)))) } Expr::SuperProp(m) => { ExprOutput::Expr(Box::alloc().init(Expression::Member(m.babelify(ctx)))) } Expr::Cond(c) => { ExprOutput::Expr(Box::alloc().init(Expression::Conditional(c.babelify(ctx)))) } Expr::Call(c) => ExprOutput::Expr(Box::alloc().init(Expression::Call(c.babelify(ctx)))), Expr::New(n) => ExprOutput::Expr(Box::alloc().init(Expression::New(n.babelify(ctx)))), Expr::Seq(s) => { ExprOutput::Expr(Box::alloc().init(Expression::Sequence(s.babelify(ctx)))) } Expr::Ident(i) => ExprOutput::Expr(Box::alloc().init(Expression::Id(i.babelify(ctx)))), Expr::Lit(lit) => { match lit { Lit::Str(s) => ExprOutput::Expr( Box::alloc().init(Expression::Literal(Literal::String(s.babelify(ctx)))), ), Lit::Bool(b) => ExprOutput::Expr( Box::alloc().init(Expression::Literal(Literal::Boolean(b.babelify(ctx)))), ), Lit::Null(n) => ExprOutput::Expr( Box::alloc().init(Expression::Literal(Literal::Null(n.babelify(ctx)))), ), Lit::Num(n) => ExprOutput::Expr( Box::alloc().init(Expression::Literal(Literal::Numeric(n.babelify(ctx)))), ), Lit::BigInt(i) => ExprOutput::Expr( Box::alloc().init(Expression::Literal(Literal::BigInt(i.babelify(ctx)))), ), Lit::Regex(r) => ExprOutput::Expr( Box::alloc().init(Expression::Literal(Literal::RegExp(r.babelify(ctx)))), ), Lit::JSXText(_) => panic!( "illegal conversion: Cannot convert {:?} to ExprOutput", &lit ), // TODO(dwoznicki): is this really illegal? } } Expr::Tpl(t) => { ExprOutput::Expr(Box::alloc().init(Expression::TemplateLiteral(t.babelify(ctx)))) } Expr::TaggedTpl(t) => { ExprOutput::Expr(Box::alloc().init(Expression::TaggedTemplate(t.babelify(ctx)))) } Expr::Arrow(a) => { ExprOutput::Expr(Box::alloc().init(Expression::ArrowFunc(a.babelify(ctx)))) } Expr::Class(c) => { ExprOutput::Expr(Box::alloc().init(Expression::Class(c.babelify(ctx)))) } Expr::Yield(y) => { ExprOutput::Expr(Box::alloc().init(Expression::Yield(y.babelify(ctx)))) } Expr::MetaProp(m) => { ExprOutput::Expr(Box::alloc().init(Expression::MetaProp(m.babelify(ctx)))) } Expr::Await(a) => { ExprOutput::Expr(Box::alloc().init(Expression::Await(a.babelify(ctx)))) } Expr::Paren(p) => { ExprOutput::Expr(Box::alloc().init(Expression::Parenthesized(p.babelify(ctx)))) } Expr::JSXElement(e) => { ExprOutput::Expr(Box::alloc().init(Expression::JSXElement(e.babelify(ctx)))) } Expr::JSXFragment(f) => { ExprOutput::Expr(Box::alloc().init(Expression::JSXFragment(f.babelify(ctx)))) } Expr::TsTypeAssertion(a) => { ExprOutput::Expr(Box::alloc().init(Expression::TSTypeAssertion(a.babelify(ctx)))) } Expr::TsNonNull(n) => { ExprOutput::Expr(Box::alloc().init(Expression::TSNonNull(n.babelify(ctx)))) } Expr::TsAs(a) => ExprOutput::Expr(Box::alloc().init(Expression::TSAs(a.babelify(ctx)))), Expr::TsInstantiation(..) => unimplemented!("Babel doesn't support this right now."), Expr::PrivateName(p) => ExprOutput::Private(p.babelify(ctx)), // TODO(dwoznicki): how does babel handle these? Expr::JSXMember(_) => panic!( "illegal conversion: Cannot convert {:?} to ExprOutput - babel has no equivalent", &self ), Expr::JSXNamespacedName(_) => panic!( "illegal conversion: Cannot convert {:?} to ExprOutput - babel has no equivalent", &self ), Expr::JSXEmpty(_) => panic!( "illegal conversion: Cannot convert {:?} to ExprOutput - babel has no equivalent", &self ), Expr::TsConstAssertion(_) => panic!( "illegal conversion: Cannot convert {:?} to ExprOutput - babel has no equivalent", &self ), Expr::TsSatisfies(_) => panic!( "illegal conversion: Cannot convert {:?} to ExprOutput - babel has no equivalent", &self ), Expr::OptChain(_) => panic!( "illegal conversion: Cannot convert {:?} to ExprOutput - babel has no equivalent", &self ), Expr::Invalid(_) => panic!( "illegal conversion: Cannot convert {:?} to ExprOutput - babel has no equivalent", &self ), } } } impl From<ExprOutput> for Expression { fn from(o: ExprOutput) -> Self { match o { ExprOutput::Expr(expr) => *expr, ExprOutput::Private(_) => panic!( "illegal conversion: Cannot convert {:?} to Expression - babel has no equivalent", &o ), } } } impl From<ExprOutput> for BinaryExprLeft { fn from(o: ExprOutput) -> Self { match o { ExprOutput::Expr(e) => BinaryExprLeft::Expr(e), ExprOutput::Private(p) => BinaryExprLeft::Private(p), } } } impl From<ExprOutput> for ObjectKey { fn from(o: ExprOutput) -> Self { match o { ExprOutput::Expr(e) => match *e { Expression::Id(i) => ObjectKey::Id(i), Expression::Literal(Literal::String(s)) => ObjectKey::String(s), Expression::Literal(Literal::Numeric(n)) => ObjectKey::Numeric(n), _ => ObjectKey::Expr(e), }, ExprOutput::Private(_) => panic!( "illegal conversion: Cannot convert {:?} to ObjectKey - babel has no equivalent", &o ), } } } impl From<ExprOutput> for MemberExprProp { fn from(o: ExprOutput) -> Self { match o { ExprOutput::Private(p) => MemberExprProp::PrivateName(p), ExprOutput::Expr(e) => match *e { Expression::Id(i) => MemberExprProp::Id(i), _ => MemberExprProp::Expr(e), }, } } } impl Babelify for ThisExpr { type Output = ThisExpression; fn babelify(self, ctx: &Context) -> Self::Output { ThisExpression { base: ctx.base(self.span), } } } impl Babelify for ArrayLit { type Output = ArrayExpression; fn babelify(self, ctx: &Context) -> Self::Output { ArrayExpression { base: ctx.base(self.span), elements: self.elems.babelify(ctx), } } } impl Babelify for ObjectLit { type Output = ObjectExpression; fn babelify(self, ctx: &Context) -> Self::Output { ObjectExpression { base: ctx.base(self.span), properties: self.props.babelify(ctx), } } } impl Babelify for PropOrSpread { type Output = ObjectExprProp; fn babelify(self, ctx: &Context) -> Self::Output { match self { PropOrSpread::Spread(s) => ObjectExprProp::Spread(s.babelify(ctx)), PropOrSpread::Prop(prop) => { let member = prop.babelify(ctx); match member { ObjectMember::Method(m) => ObjectExprProp::Method(m), ObjectMember::Prop(p) => ObjectExprProp::Prop(p), } } } } } impl Babelify for SpreadElement { type Output = BabelSpreadElement; fn babelify(self, ctx: &Context) -> Self::Output { BabelSpreadElement { base: ctx.base(self.span()), argument: Box::alloc().init(self.expr.babelify(ctx).into()), } } } impl Babelify for UnaryExpr { type Output = UnaryExpression; fn babelify(self, ctx: &Context) -> Self::Output { UnaryExpression { base: ctx.base(self.span), operator: self.op.babelify(ctx), argument: Box::alloc().init(self.arg.babelify(ctx).into()), prefix: true, } } } impl Babelify for UpdateExpr { type Output = UpdateExpression; fn babelify(self, ctx: &Context) -> Self::Output { UpdateExpression { base: ctx.base(self.span), operator: self.op.babelify(ctx), prefix: self.prefix, argument: Box::alloc().init(self.arg.babelify(ctx).into()), } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum BinaryOrLogicalExpr { Binary(BinaryExpression), Logical(LogicalExpression), } impl Babelify for BinExpr { type Output = BinaryOrLogicalExpr; fn babelify(self, ctx: &Context) -> Self::Output { match self.op { BinaryOp::LogicalOr | BinaryOp::LogicalAnd | BinaryOp::NullishCoalescing => { BinaryOrLogicalExpr::Logical(LogicalExpression { base: ctx.base(self.span), operator: self.op.babelify(ctx).into(), left: Box::alloc().init(self.left.babelify(ctx).into()), right: Box::alloc().init(self.right.babelify(ctx).into()), }) } _ => BinaryOrLogicalExpr::Binary(BinaryExpression { base: ctx.base(self.span), operator: self.op.babelify(ctx).into(), left: Box::alloc().init(self.left.babelify(ctx).into()), right: Box::alloc().init(self.right.babelify(ctx).into()), }), } // BinaryExpression { // base: ctx.base(self.span), // operator: self.op.babelify(ctx).into(), // left: Box::alloc().init(self.left.babelify(ctx).into()), // right: Box::alloc().init(self.right.babelify(ctx).into()), // } } } impl Babelify for FnExpr { type Output = FunctionExpression; fn babelify(self, ctx: &Context) -> Self::Output { FunctionExpression { id: self.ident.map(|id| id.babelify(ctx)), ..self.function.babelify(ctx) } } } impl Babelify for ClassExpr { type Output = ClassExpression; fn babelify(self, ctx: &Context) -> Self::Output { ClassExpression { id: self.ident.map(|id| id.babelify(ctx)), ..self.class.babelify(ctx) } } } impl Babelify for AssignExpr { type Output = AssignmentExpression; fn babelify(self, ctx: &Context) -> Self::Output { AssignmentExpression { base: ctx.base(self.span), operator: self.op.as_str().into(), left: Box::alloc().init(self.left.babelify(ctx)), right: Box::alloc().init(self.right.babelify(ctx).into()), } } } impl Babelify for MemberExpr { type Output = MemberExpression; fn babelify(self, ctx: &Context) -> Self::Output { let computed = self.prop.is_computed(); MemberExpression { base: ctx.base(self.span), object: Box::alloc().init(self.obj.babelify(ctx).into()), property: Box::alloc().init(self.prop.babelify(ctx)), computed, optional: Default::default(), } } } impl Babelify for MemberProp { type Output = MemberExprProp; fn babelify(self, ctx: &Context) -> Self::Output { match self { Self::Computed(c) => MemberExprProp::Expr(c.babelify(ctx).into()), Self::Ident(i) => MemberExprProp::Id(i.babelify(ctx)), Self::PrivateName(p) => MemberExprProp::PrivateName(p.babelify(ctx)), } } } impl Babelify for SuperPropExpr { type Output = MemberExpression; fn babelify(self, ctx: &Context) -> Self::Output { let computed = self.prop.is_computed(); MemberExpression { base: ctx.base(self.span), object: Box::alloc().init(Expression::Super(self.obj.babelify(ctx))), property: Box::alloc().init(self.prop.babelify(ctx)), computed, optional: Default::default(), } } } impl Babelify for SuperProp { type Output = MemberExprProp; fn babelify(self, ctx: &Context) -> Self::Output { match self { Self::Computed(c) => MemberExprProp::Expr(c.babelify(ctx).into()), Self::Ident(i) => MemberExprProp::Id(i.babelify(ctx)), } } } impl Babelify for CondExpr { type Output = ConditionalExpression; fn babelify(self, ctx: &Context) -> Self::Output { ConditionalExpression { base: ctx.base(self.span), test: Box::alloc().init(self.test.babelify(ctx).into()), consequent: Box::alloc().init(self.cons.babelify(ctx).into()), alternate: Box::alloc().init(self.alt.babelify(ctx).into()), } } } impl Babelify for CallExpr { type Output = CallExpression; fn babelify(self, ctx: &Context) -> Self::Output { CallExpression { base: ctx.base(self.span), callee: Box::alloc().init(self.callee.babelify(ctx).into()), arguments: self .args .into_iter() .map(|arg| arg.babelify(ctx).into()) .collect(), type_parameters: self.type_args.map(|t| t.babelify(ctx)), type_arguments: Default::default(), optional: Default::default(), } } } impl Babelify for NewExpr { type Output = NewExpression; fn babelify(self, ctx: &Context) -> Self::Output { NewExpression { base: ctx.base(self.span), callee: BabelCallee::Expr(Box::alloc().init(self.callee.babelify(ctx).into())), arguments: match self.args { Some(args) => args .into_iter() .map(|arg| arg.babelify(ctx).into()) .collect(), None => Vec::new(), }, type_parameters: self.type_args.map(|t| t.babelify(ctx)), type_arguments: Default::default(), optional: Default::default(), } } } impl Babelify for SeqExpr { type Output = SequenceExpression; fn babelify(self, ctx: &Context) -> Self::Output { SequenceExpression { base: ctx.base(self.span), expressions: self .exprs .into_iter() .map(|expr| Box::alloc().init(expr.babelify(ctx).into())) .collect(), } } } impl Babelify for ArrowExpr { type Output = ArrowFunctionExpression; fn babelify(self, ctx: &Context) -> Self::Output { ArrowFunctionExpression { base: ctx.base(self.span), params: self .params .into_iter() .map(|p| p.babelify(ctx).into()) .collect(), body: Box::alloc().init(self.body.babelify(ctx)), is_async: self.is_async, expression: match Flavor::current() { Flavor::Babel => Default::default(), Flavor::Acorn { .. } => true, }, generator: self.is_generator, return_type: self .return_type .map(|t| Box::alloc().init(t.babelify(ctx).into())), type_parameters: self.type_params.map(|t| t.babelify(ctx).into()), } } } impl Babelify for YieldExpr { type Output = YieldExpression; fn babelify(self, ctx: &Context) -> Self::Output { YieldExpression { base: ctx.base(self.span), argument: self.arg.map(|a| Box::alloc().init(a.babelify(ctx).into())), delegate: self.delegate, } } } impl Babelify for MetaPropExpr { type Output = MetaProperty; fn babelify(self, ctx: &Context) -> Self::Output { let (meta, property) = match self.kind { MetaPropKind::ImportMeta => ( Ident { span: Span { hi: self.span.hi - BytePos(5), ..self.span }, sym: "import".into(), ..Default::default() } .babelify(ctx), Ident { span: Span { lo: self.span.lo + BytePos(7), ..self.span }, sym: "meta".into(), ..Default::default() } .babelify(ctx), ), MetaPropKind::NewTarget => ( Ident { span: Span { hi: self.span.hi - BytePos(7), ..self.span }, sym: "new".into(), ..Default::default() } .babelify(ctx), Ident { span: Span { hi: self.span.hi + BytePos(4), ..self.span }, sym: "target".into(), ..Default::default() } .babelify(ctx), ), }; MetaProperty { base: ctx.base(self.span()), meta, property, } } } impl Babelify for AwaitExpr { type Output = AwaitExpression; fn babelify(self, ctx: &Context) -> Self::Output { AwaitExpression { base: ctx.base(self.span), argument: Box::alloc().init(self.arg.babelify(ctx).into()), } } } impl Babelify for Tpl { type Output = TemplateLiteral; fn babelify(self, ctx: &Context) -> Self::Output { TemplateLiteral { base: ctx.base(self.span), expressions: self .exprs .into_iter() .map(|e| TemplateLiteralExpr::Expr(Box::alloc().init(e.babelify(ctx).into()))) .collect(), quasis: self.quasis.babelify(ctx), } } } impl Babelify for TaggedTpl { type Output = TaggedTemplateExpression; fn babelify(self, ctx: &Context) -> Self::Output { TaggedTemplateExpression { base: ctx.base(self.span), tag: Box::alloc().init(self.tag.babelify(ctx).into()), quasi: self.tpl.babelify(ctx), type_parameters: self .type_params .map(|t| TaggedTemplateExprTypeParams::TS(t.babelify(ctx))), } } } impl Babelify for TplElement { type Output = TemplateElement; fn babelify(self, ctx: &Context) -> Self::Output { TemplateElement { base: ctx.base(self.span), tail: self.tail, value: TemplateElVal { raw: self.raw, cooked: self.cooked, }, } } } impl Babelify for ParenExpr { type Output = ParenthesizedExpression; fn babelify(self, ctx: &Context) -> Self::Output { ParenthesizedExpression { base: ctx.base(self.span), expression: Box::alloc().init(self.expr.babelify(ctx).into()), } } } impl Babelify for Callee { type Output = Expression; fn babelify(self, ctx: &Context) -> Self::Output { match self { Callee::Expr(e) => e.babelify(ctx).into(), Callee::Super(s) => Expression::Super(s.babelify(ctx)), Callee::Import(i) => Expression::Import(i.babelify(ctx)), } } } impl Babelify for Super { type Output = BabelSuper; fn babelify(self, ctx: &Context) -> Self::Output { BabelSuper { base: ctx.base(self.span), } } } impl Babelify for Import { type Output = BabelImport; fn babelify(self, ctx: &Context) -> Self::Output { BabelImport { base: ctx.base(self.span), } } } impl Babelify for ExprOrSpread { type Output = ArrayExprEl; fn babelify(self, ctx: &Context) -> Self::Output { match self.spread { Some(_) => ArrayExprEl::Spread(BabelSpreadElement { base: ctx.base(self.span()), argument: Box::alloc().init(self.expr.babelify(ctx).into()), }), None => ArrayExprEl::Expr(Box::alloc().init(self.expr.babelify(ctx).into())), } } } impl Babelify for BlockStmtOrExpr { type Output = ArrowFuncExprBody; fn babelify(self, ctx: &Context) -> Self::Output { match self { BlockStmtOrExpr::BlockStmt(b) => ArrowFuncExprBody::Block(b.babelify(ctx)), BlockStmtOrExpr::Expr(e) => { ArrowFuncExprBody::Expr(Box::alloc().init(e.babelify(ctx).into())) } } } } impl Babelify for AssignTarget { type Output = LVal; fn babelify(self, ctx: &Context) -> Self::Output { match self { AssignTarget::Simple(s) => s.babelify(ctx), AssignTarget::Pat(p) => p.babelify(ctx), } } } impl Babelify for SimpleAssignTarget { type Output = LVal; fn babelify(self, ctx: &Context) -> Self::Output { match self { SimpleAssignTarget::Ident(i) => LVal::Id(i.babelify(ctx)), SimpleAssignTarget::Member(m) => LVal::MemberExpr(m.babelify(ctx)), SimpleAssignTarget::SuperProp(s) => LVal::MemberExpr(s.babelify(ctx)), _ => unreachable!(), } } } impl Babelify for AssignTargetPat { type Output = LVal; fn babelify(self, ctx: &Context) -> Self::Output { match self { AssignTargetPat::Array(a) => LVal::ArrayPat(a.babelify(ctx)), AssignTargetPat::Object(o) => LVal::ObjectPat(o.babelify(ctx)), AssignTargetPat::Invalid(_) => todo!(), } } } // NOTE: OptChainExpr does not appear to have an official Babel AST node yet. // #[ast_node("OptionalChainingExpression")] // #[derive(Eq, Hash, EqIgnoreSpan)] // #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] // pub struct OptChainExpr { // pub span: Span, // pub question_dot_token: Span, // pub expr: Box<Expr>, // } //
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/babelify/function.rs
Rust
use copyless::BoxHelper; use swc_ecma_ast::{Function, Param, ParamOrTsParamProp, Pat}; use swc_estree_ast::{ ArrayPattern, AssignmentPattern, FunctionExpression, Identifier, ObjectPattern, Param as BabelParam, Pattern, RestElement, }; use crate::babelify::{Babelify, Context}; impl Babelify for Function { type Output = FunctionExpression; fn babelify(self, ctx: &Context) -> Self::Output { FunctionExpression { base: ctx.base(self.span), params: self.params.babelify(ctx), body: self.body.unwrap().babelify(ctx), generator: Some(self.is_generator), is_async: Some(self.is_async), type_parameters: self.type_params.map(|t| t.babelify(ctx).into()), return_type: self .return_type .map(|t| Box::alloc().init(t.babelify(ctx).into())), id: None, } } } impl Babelify for Param { type Output = BabelParam; fn babelify(self, ctx: &Context) -> Self::Output { match self.pat { Pat::Ident(i) => BabelParam::Id(Identifier { base: ctx.base(self.span), decorators: Some(self.decorators.babelify(ctx)), ..i.babelify(ctx) }), Pat::Array(a) => BabelParam::Pat(Pattern::Array(ArrayPattern { base: ctx.base(self.span), decorators: Some(self.decorators.babelify(ctx)), ..a.babelify(ctx) })), Pat::Rest(r) => BabelParam::Rest(RestElement { base: ctx.base(self.span), decorators: Some(self.decorators.babelify(ctx)), ..r.babelify(ctx) }), Pat::Object(o) => BabelParam::Pat(Pattern::Object(ObjectPattern { base: ctx.base(self.span), decorators: Some(self.decorators.babelify(ctx)), ..o.babelify(ctx) })), Pat::Assign(a) => BabelParam::Pat(Pattern::Assignment(AssignmentPattern { base: ctx.base(self.span), decorators: Some(self.decorators.babelify(ctx)), ..a.babelify(ctx) })), Pat::Expr(_) => panic!( "illegal conversion: Cannot convert {:?} to BabelParam", &self.pat ), Pat::Invalid(_) => panic!( "illegal conversion: Cannot convert {:?} to BabelParam", &self.pat ), } } } impl Babelify for ParamOrTsParamProp { type Output = BabelParam; fn babelify(self, ctx: &Context) -> Self::Output { match self { ParamOrTsParamProp::TsParamProp(p) => BabelParam::TSProp(p.babelify(ctx)), ParamOrTsParamProp::Param(p) => p.babelify(ctx), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/babelify/ident.rs
Rust
use copyless::BoxHelper; use swc_ecma_ast::{BindingIdent, Ident, IdentName, PrivateName}; use swc_estree_ast::{Identifier, PrivateName as BabelPrivateName}; use crate::babelify::{Babelify, Context}; impl Babelify for BindingIdent { type Output = Identifier; fn babelify(self, ctx: &Context) -> Self::Output { Identifier { type_annotation: self .type_ann .map(|ann| Box::alloc().init(ann.babelify(ctx).into())), ..self.id.babelify(ctx) } } } impl Babelify for Ident { type Output = Identifier; fn babelify(self, ctx: &Context) -> Self::Output { Identifier { base: ctx.base(self.span), name: self.sym, optional: Some(self.optional), decorators: Default::default(), type_annotation: Default::default(), } } } impl Babelify for IdentName { type Output = Identifier; fn babelify(self, ctx: &Context) -> Self::Output { Identifier { base: ctx.base(self.span), name: self.sym, optional: Default::default(), decorators: Default::default(), type_annotation: Default::default(), } } } impl Babelify for PrivateName { type Output = BabelPrivateName; fn babelify(self, ctx: &Context) -> Self::Output { BabelPrivateName { base: ctx.base(self.span), id: Identifier { base: ctx.base(self.span), name: self.name, decorators: Default::default(), optional: Default::default(), type_annotation: None, }, } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/babelify/jsx.rs
Rust
use copyless::BoxHelper; use swc_common::{BytePos, Span, Spanned}; use swc_ecma_ast::{ JSXAttr, JSXAttrName, JSXAttrOrSpread, JSXAttrValue, JSXClosingElement, JSXClosingFragment, JSXElement, JSXElementChild, JSXElementName, JSXEmptyExpr, JSXExpr, JSXExprContainer, JSXFragment, JSXMemberExpr, JSXNamespacedName, JSXObject, JSXOpeningElement, JSXOpeningFragment, JSXSpreadChild, JSXText, Lit, }; use swc_estree_ast::{ flavor::Flavor, JSXAttrName as BabelJSXAttrName, JSXAttrVal, JSXAttribute, JSXClosingElement as BabelJSXClosingElement, JSXClosingFragment as BabelJSXClosingFragment, JSXElement as BabelJSXElement, JSXElementChild as BabelJSXElementChild, JSXElementName as BabelJSXElementName, JSXEmptyExpression, JSXExprContainerExpr, JSXExpressionContainer, JSXFragment as BabelJSXFragment, JSXMemberExprObject, JSXMemberExpression, JSXNamespacedName as BabelJSXNamespacedName, JSXOpeningElAttr, JSXOpeningElement as BabelJSXOpeningElement, JSXOpeningFragment as BabelJSXOpeningFragment, JSXSpreadAttribute, JSXSpreadChild as BabelJSXSpreadChild, JSXText as BabelJSXText, }; use crate::babelify::{Babelify, Context}; impl Babelify for JSXObject { type Output = JSXMemberExprObject; fn babelify(self, ctx: &Context) -> Self::Output { match self { JSXObject::JSXMemberExpr(e) => JSXMemberExprObject::Expr(e.babelify(ctx)), JSXObject::Ident(i) => JSXMemberExprObject::Id(i.babelify(ctx).into()), } } } impl Babelify for JSXMemberExpr { type Output = JSXMemberExpression; fn babelify(self, ctx: &Context) -> Self::Output { JSXMemberExpression { base: ctx.base(self.span()), object: Box::alloc().init(self.obj.babelify(ctx)), property: self.prop.babelify(ctx).into(), } } } impl Babelify for JSXNamespacedName { type Output = BabelJSXNamespacedName; fn babelify(self, ctx: &Context) -> Self::Output { BabelJSXNamespacedName { base: ctx.base(self.span()), namespace: self.ns.babelify(ctx).into(), name: self.name.babelify(ctx).into(), } } } impl Babelify for JSXEmptyExpr { type Output = JSXEmptyExpression; fn babelify(self, ctx: &Context) -> Self::Output { JSXEmptyExpression { base: ctx.base(self.span), } } } impl Babelify for JSXExprContainer { type Output = JSXExpressionContainer; fn babelify(self, ctx: &Context) -> Self::Output { JSXExpressionContainer { base: ctx.base(self.span), expression: self.expr.babelify(ctx), } } } impl Babelify for JSXExpr { type Output = JSXExprContainerExpr; fn babelify(self, ctx: &Context) -> Self::Output { match self { JSXExpr::JSXEmptyExpr(e) => JSXExprContainerExpr::Empty(e.babelify(ctx)), JSXExpr::Expr(e) => { JSXExprContainerExpr::Expr(Box::alloc().init(e.babelify(ctx).into())) } } } } impl Babelify for JSXSpreadChild { type Output = BabelJSXSpreadChild; fn babelify(self, ctx: &Context) -> Self::Output { BabelJSXSpreadChild { base: ctx.base(self.span), expression: Box::alloc().init(self.expr.babelify(ctx).into()), } } } impl Babelify for JSXElementName { type Output = BabelJSXElementName; fn babelify(self, ctx: &Context) -> Self::Output { match self { JSXElementName::Ident(i) => BabelJSXElementName::Id(i.babelify(ctx).into()), JSXElementName::JSXMemberExpr(e) => BabelJSXElementName::Expr(e.babelify(ctx)), JSXElementName::JSXNamespacedName(n) => BabelJSXElementName::Name(n.babelify(ctx)), } } } impl Babelify for JSXOpeningElement { type Output = BabelJSXOpeningElement; fn babelify(self, ctx: &Context) -> Self::Output { BabelJSXOpeningElement { base: ctx.base(self.span), name: self.name.babelify(ctx), attributes: self.attrs.babelify(ctx), self_closing: self.self_closing, type_parameters: self.type_args.map(|arg| arg.babelify(ctx).into()), } } } impl Babelify for JSXAttrOrSpread { type Output = JSXOpeningElAttr; fn babelify(self, ctx: &Context) -> Self::Output { match self { JSXAttrOrSpread::JSXAttr(a) => JSXOpeningElAttr::Attr(a.babelify(ctx)), JSXAttrOrSpread::SpreadElement(spread) => { // For JSX spread elements, babel includes the curly braces, and swc // does not. So we extend the span to include the braces here. let span = extend_spread_span_to_braces(spread.span(), ctx); JSXOpeningElAttr::Spread(JSXSpreadAttribute { base: ctx.base(span), argument: Box::alloc().init(spread.expr.babelify(ctx).into()), }) } } } } fn extend_spread_span_to_braces(sp: Span, ctx: &Context) -> Span { let mut span = sp; let _ = ctx.cm.with_span_to_prev_source(sp, |prev_source| { let mut num_chars = 0; for c in prev_source.chars().rev() { num_chars += 1; if c == '{' { span = span.with_lo(span.lo - BytePos(num_chars)); } else if !c.is_whitespace() { break; } } }); let _ = ctx.cm.with_span_to_next_source(sp, |next_source| { let mut num_chars = 0; for c in next_source.chars() { num_chars += 1; if c == '}' { span = span.with_hi(span.hi + BytePos(num_chars)); } else if !c.is_whitespace() { break; } } }); span } impl Babelify for JSXClosingElement { type Output = BabelJSXClosingElement; fn babelify(self, ctx: &Context) -> Self::Output { BabelJSXClosingElement { base: ctx.base(self.span), name: self.name.babelify(ctx), } } } impl Babelify for JSXAttr { type Output = JSXAttribute; fn babelify(self, ctx: &Context) -> Self::Output { JSXAttribute { base: ctx.base(self.span), name: self.name.babelify(ctx), value: self.value.map(|val| val.babelify(ctx)), } } } impl Babelify for JSXAttrName { type Output = BabelJSXAttrName; fn babelify(self, ctx: &Context) -> Self::Output { match self { JSXAttrName::Ident(i) => BabelJSXAttrName::Id(i.babelify(ctx).into()), JSXAttrName::JSXNamespacedName(n) => BabelJSXAttrName::Name(n.babelify(ctx)), } } } impl Babelify for JSXAttrValue { type Output = JSXAttrVal; fn babelify(self, ctx: &Context) -> Self::Output { match self { JSXAttrValue::Lit(lit) => { // TODO(dwoznicki): Babel only seems to accept string literals here. Is that // right? match lit { Lit::Str(s) => JSXAttrVal::String(s.babelify(ctx)), _ => panic!( "illegal conversion: Cannot convert {:?} to JsxAttrVal::Lit", &lit ), } } JSXAttrValue::JSXExprContainer(e) => JSXAttrVal::Expr(e.babelify(ctx)), JSXAttrValue::JSXElement(e) => JSXAttrVal::Element(e.babelify(ctx)), JSXAttrValue::JSXFragment(f) => JSXAttrVal::Fragment(f.babelify(ctx)), } } } impl Babelify for JSXText { type Output = BabelJSXText; fn babelify(self, ctx: &Context) -> Self::Output { BabelJSXText { base: ctx.base(self.span), value: self.value, } } } impl Babelify for JSXElement { type Output = BabelJSXElement; fn babelify(self, ctx: &Context) -> Self::Output { let self_closing = match Flavor::current() { Flavor::Babel => None, Flavor::Acorn { .. } => Some(self.closing.is_some()), }; BabelJSXElement { base: ctx.base(self.span), opening_element: self.opening.babelify(ctx), closing_element: self.closing.map(|el| el.babelify(ctx)), children: self.children.babelify(ctx), self_closing, } } } impl Babelify for JSXElementChild { type Output = BabelJSXElementChild; fn babelify(self, ctx: &Context) -> Self::Output { match self { JSXElementChild::JSXText(t) => BabelJSXElementChild::Text(t.babelify(ctx)), JSXElementChild::JSXExprContainer(e) => BabelJSXElementChild::Expr(e.babelify(ctx)), JSXElementChild::JSXSpreadChild(s) => BabelJSXElementChild::Spread(s.babelify(ctx)), JSXElementChild::JSXElement(e) => BabelJSXElementChild::Element(e.babelify(ctx)), JSXElementChild::JSXFragment(f) => BabelJSXElementChild::Fragment(f.babelify(ctx)), } } } impl Babelify for JSXFragment { type Output = BabelJSXFragment; fn babelify(self, ctx: &Context) -> Self::Output { BabelJSXFragment { base: ctx.base(self.span), opening_fragment: self.opening.babelify(ctx), closing_fragment: self.closing.babelify(ctx), children: self.children.babelify(ctx), } } } impl Babelify for JSXOpeningFragment { type Output = BabelJSXOpeningFragment; fn babelify(self, ctx: &Context) -> Self::Output { BabelJSXOpeningFragment { base: ctx.base(self.span), } } } impl Babelify for JSXClosingFragment { type Output = BabelJSXClosingFragment; fn babelify(self, ctx: &Context) -> Self::Output { BabelJSXClosingFragment { base: ctx.base(self.span), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/babelify/lit.rs
Rust
use serde::{Deserialize, Serialize}; use swc_ecma_ast::{BigInt, Bool, Lit, Null, Number, Regex, Str}; use swc_estree_ast::{ BigIntLiteral, BooleanLiteral, JSXText as BabelJSXText, Literal, NullLiteral, NumericLiteral, RegExpLiteral, StringLiteral, }; use crate::babelify::{Babelify, Context}; #[derive(Debug, Clone, Serialize, Deserialize)] pub enum LitOutput { Lit(Literal), JSX(BabelJSXText), } impl Babelify for Lit { type Output = LitOutput; fn babelify(self, ctx: &Context) -> Self::Output { match self { Lit::Str(s) => LitOutput::Lit(Literal::String(s.babelify(ctx))), Lit::Bool(b) => LitOutput::Lit(Literal::Boolean(b.babelify(ctx))), Lit::Null(n) => LitOutput::Lit(Literal::Null(n.babelify(ctx))), Lit::Num(n) => LitOutput::Lit(Literal::Numeric(n.babelify(ctx))), Lit::BigInt(i) => LitOutput::Lit(Literal::BigInt(i.babelify(ctx))), Lit::Regex(r) => LitOutput::Lit(Literal::RegExp(r.babelify(ctx))), Lit::JSXText(t) => LitOutput::JSX(t.babelify(ctx)), } } } impl Babelify for Str { type Output = StringLiteral; fn babelify(self, ctx: &Context) -> Self::Output { StringLiteral { base: ctx.base(self.span), value: self.value, // TODO improve me raw: match self.raw { Some(value) => value, _ => "".into(), }, } } } impl Babelify for Bool { type Output = BooleanLiteral; fn babelify(self, ctx: &Context) -> Self::Output { BooleanLiteral { base: ctx.base(self.span), value: self.value, } } } impl Babelify for Null { type Output = NullLiteral; fn babelify(self, ctx: &Context) -> Self::Output { NullLiteral { base: ctx.base(self.span), } } } impl Babelify for Number { type Output = NumericLiteral; fn babelify(self, ctx: &Context) -> Self::Output { NumericLiteral { base: ctx.base(self.span), value: self.value, } } } impl Babelify for BigInt { type Output = BigIntLiteral; fn babelify(self, ctx: &Context) -> Self::Output { BigIntLiteral { base: ctx.base(self.span), value: self.value.to_string(), // TODO improve me raw: match self.raw { Some(value) => value, _ => "".into(), }, } } } impl Babelify for Regex { type Output = RegExpLiteral; fn babelify(self, ctx: &Context) -> Self::Output { RegExpLiteral { base: ctx.base(self.span), pattern: self.exp, flags: self.flags, } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/babelify/mod.rs
Rust
use serde::{de::DeserializeOwned, Serialize}; use swc_common::{ comments::{CommentKind, Comments}, sync::Lrc, BytePos, SourceFile, SourceMap, Span, }; use swc_ecma_ast::Class; use swc_estree_ast::{flavor::Flavor, BaseComment, BaseNode, Comment, CommentType, LineCol, Loc}; use swc_node_comments::SwcComments; mod class; mod decl; mod expr; mod function; mod ident; mod jsx; mod lit; mod module; mod module_decl; mod operators; mod pat; mod prop; mod stmt; mod typescript; #[derive(Clone)] pub struct Context { pub fm: Lrc<SourceFile>, pub cm: Lrc<SourceMap>, pub comments: SwcComments, } impl Context { /// Byte offset starting from the 0. (counted separately for each file) fn offset(&self, span: Span) -> (Option<u32>, Option<u32>) { if span.is_dummy() { return (None, None); } let (start, end) = self.cm.span_to_char_offset(&self.fm, span); (Some(start), Some(end)) } fn line_col(&self, pos: BytePos) -> Option<LineCol> { let loc = self.cm.lookup_char_pos_with(self.fm.clone(), pos); Some(LineCol { line: loc.line, column: loc.col.0, }) } fn loc(&self, span: Span) -> Option<Loc> { if span.is_dummy() { return None; } if !Flavor::current().emit_loc() { return None; } let start = self.line_col(span.lo)?; let end = self.line_col(span.hi)?; Some(Loc { start, end }) } fn convert_comments(&self, comments: Vec<swc_common::comments::Comment>) -> Vec<Comment> { comments .into_iter() .map(|c| { let (start, end) = self.offset(c.span); let loc = self.loc(c.span).unwrap_or_else(Loc::dummy); let comment = BaseComment { type_: match c.kind { CommentKind::Line => CommentType::Line, CommentKind::Block => CommentType::Block, }, value: c.text, start: start.unwrap_or_default(), end: end.unwrap_or_default(), loc, }; match c.kind { CommentKind::Line => Comment::Line(comment), CommentKind::Block => Comment::Block(comment), } }) .collect() } /// Creates a [BaseNode] from `span`. /// /// Note that we removes comment from the comment map because `.babelify` /// takes `self`. (not reference) fn base(&self, span: Span) -> BaseNode { let leading_comments = self .comments .take_leading(span.lo) .map(|v| self.convert_comments(v)) .unwrap_or_default(); let trailing_comments = self .comments .take_trailing(span.hi) .map(|v| self.convert_comments(v)) .unwrap_or_default(); let (start, end) = self.offset(span); let loc = self.loc(span); BaseNode { leading_comments, // TODO(kdy1): Use this field. inner_comments: Default::default(), trailing_comments, start, end, loc, range: if matches!(Flavor::current(), Flavor::Acorn { .. }) { match (start, end) { (Some(start), Some(end)) => Some([start, end]), _ => None, } } else { None }, } } } pub trait Babelify: Send + Sync { type Output: Serialize + DeserializeOwned + Send + Sync; fn parallel(_cnt: usize) -> bool { false } fn babelify(self, ctx: &Context) -> Self::Output; } impl<T> Babelify for Vec<T> where T: Babelify, { type Output = Vec<T::Output>; fn babelify(self, ctx: &Context) -> Self::Output { self.into_iter().map(|v| v.babelify(ctx)).collect() } } impl<T> Babelify for Option<T> where T: Babelify, { type Output = Option<T::Output>; fn babelify(self, ctx: &Context) -> Self::Output { self.map(|v| v.babelify(ctx)) } } impl<T> Babelify for Box<T> where T: Babelify, { type Output = T::Output; fn babelify(self, ctx: &Context) -> Self::Output { (*self).babelify(ctx) } } fn extract_class_body_span(class: &Class, ctx: &Context) -> Span { let sp = ctx.cm.span_take_while(class.span, |ch| *ch != '{'); class.span.with_lo(sp.hi()) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/babelify/module.rs
Rust
use serde::{Deserialize, Serialize}; use swc_common::{comments::Comment, Span}; use swc_ecma_ast::{Module, ModuleItem, Program, Script}; use swc_ecma_visit::{Visit, VisitWith}; use swc_estree_ast::{ flavor::Flavor, BaseNode, File, InterpreterDirective, LineCol, Loc, ModuleDeclaration, Program as BabelProgram, SrcType, Statement, }; use swc_node_comments::SwcComments; use crate::babelify::{Babelify, Context}; impl Babelify for Program { type Output = File; fn babelify(self, ctx: &Context) -> Self::Output { let comments = extract_all_comments(&self, ctx); let program = match self { Program::Module(module) => module.babelify(ctx), Program::Script(script) => script.babelify(ctx), // TODO: reenable once experimental_metadata breaking change is merged // _ => unreachable!(), }; File { base: BaseNode { leading_comments: Default::default(), inner_comments: Default::default(), trailing_comments: Default::default(), start: program.base.start, end: program.base.end, loc: program.base.loc, range: if matches!(Flavor::current(), Flavor::Acorn { .. }) { match (program.base.start, program.base.end) { (Some(start), Some(end)) => Some([start, end]), _ => None, } } else { None }, }, program, comments: Some(ctx.convert_comments(comments)), tokens: Default::default(), } } } impl Babelify for Module { type Output = BabelProgram; fn babelify(self, ctx: &Context) -> Self::Output { let span = if has_comment_first_line(self.span, ctx) { self.span.with_lo(ctx.fm.start_pos) } else { self.span }; BabelProgram { base: base_with_trailing_newline(span, ctx), source_type: SrcType::Module, body: self .body .into_iter() .map(|stmt| stmt.babelify(ctx).into()) .collect(), interpreter: self.shebang.map(|s| InterpreterDirective { base: ctx.base(extract_shebang_span(span, ctx)), value: s, }), directives: Default::default(), source_file: Default::default(), comments: Default::default(), } } } impl Babelify for Script { type Output = BabelProgram; fn babelify(self, ctx: &Context) -> Self::Output { let span = if has_comment_first_line(self.span, ctx) { self.span.with_lo(ctx.fm.start_pos) } else { self.span }; BabelProgram { base: base_with_trailing_newline(span, ctx), source_type: SrcType::Script, body: self.body.babelify(ctx), interpreter: self.shebang.map(|s| InterpreterDirective { base: ctx.base(extract_shebang_span(span, ctx)), value: s, }), directives: Default::default(), source_file: Default::default(), comments: Default::default(), } } } /// Babel adds a trailing newline to the end of files when parsing, while swc /// truncates trailing whitespace. In order to get the converted base node to /// locations to match babel, we imitate the trailing newline for Script and /// Module nodes. fn base_with_trailing_newline(span: Span, ctx: &Context) -> BaseNode { let mut base = ctx.base(span); base.end = base.end.map(|num| num + 1); base.loc = base.loc.map(|loc| Loc { end: LineCol { line: loc.end.line + 1, column: 0, }, ..loc }); base.range = base.range.map(|range| [range[0], range[1] + 1]); base } /// Should return true if the first line in parsed file is a comment. /// Required because babel and swc have slightly different handlings for first /// line comments. Swc ignores them and starts the program on the next line /// down, while babel includes them in the file start/end. fn has_comment_first_line(sp: Span, ctx: &Context) -> bool { if let Some(comments) = ctx.comments.leading.get(&sp.hi) { !comments .first() .map(|c| c.span.lo == ctx.fm.start_pos) .unwrap_or(false) } else { true } } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum ModuleItemOutput { ModuleDecl(ModuleDeclaration), Stmt(Statement), } impl Babelify for ModuleItem { type Output = ModuleItemOutput; fn parallel(cnt: usize) -> bool { cnt >= 32 } fn babelify(self, ctx: &Context) -> Self::Output { match self { ModuleItem::ModuleDecl(d) => ModuleItemOutput::ModuleDecl(d.babelify(ctx).into()), ModuleItem::Stmt(s) => ModuleItemOutput::Stmt(s.babelify(ctx)), } } } impl From<ModuleItemOutput> for Statement { fn from(m: ModuleItemOutput) -> Self { match m { ModuleItemOutput::Stmt(stmt) => stmt, ModuleItemOutput::ModuleDecl(decl) => match decl { ModuleDeclaration::ExportAll(e) => Statement::ExportAllDecl(e), ModuleDeclaration::ExportDefault(e) => Statement::ExportDefaultDecl(e), ModuleDeclaration::ExportNamed(e) => Statement::ExportNamedDecl(e), ModuleDeclaration::Import(i) => Statement::ImportDecl(i), }, } } } fn extract_shebang_span(span: Span, ctx: &Context) -> Span { ctx.cm.span_take_while(span, |ch| *ch != '\n') } fn extract_all_comments(program: &Program, ctx: &Context) -> Vec<Comment> { let mut collector = CommentCollector { comments: ctx.comments.clone(), collected: Vec::new(), }; program.visit_with(&mut collector); collector.collected } struct CommentCollector { comments: SwcComments, collected: Vec<Comment>, } impl Visit for CommentCollector { fn visit_span(&mut self, sp: &Span) { let mut span_comments: Vec<Comment> = Vec::new(); // Comments must be deduped since it's possible for a single comment to show up // multiple times since they are not removed from the comments map. // For example, this happens when the first line in a file is a comment. if let Some(comments) = self.comments.leading.get(&sp.lo) { for comment in comments.iter() { if !self.collected.iter().any(|c| *c == *comment) { span_comments.push(comment.clone()); } } } if let Some(comments) = self.comments.trailing.get(&sp.hi) { for comment in comments.iter() { if !self.collected.iter().any(|c| *c == *comment) { span_comments.push(comment.clone()); } } } self.collected.append(&mut span_comments); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/babelify/module_decl.rs
Rust
use copyless::BoxHelper; use serde::{Deserialize, Serialize}; use swc_ecma_ast::{ DefaultDecl, ExportAll, ExportDecl, ExportDefaultDecl, ExportDefaultExpr, ExportDefaultSpecifier, ExportNamedSpecifier, ExportNamespaceSpecifier, ExportSpecifier, Expr, ImportDecl, ImportDefaultSpecifier, ImportNamedSpecifier, ImportSpecifier, ImportStarAsSpecifier, Lit, ModuleDecl, ModuleExportName, NamedExport, ObjectLit, Prop, PropName, PropOrSpread, }; use swc_estree_ast::{ ExportAllDeclaration, ExportDefaultDeclType, ExportDefaultDeclaration, ExportDefaultSpecifier as BabelExportDefaultSpecifier, ExportKind, ExportNamedDeclaration, ExportNamespaceSpecifier as BabelExportNamespaceSpecifier, ExportSpecifier as BabelExportSpecifier, ExportSpecifierType, IdOrString, ImportAttribute, ImportDeclaration, ImportDefaultSpecifier as BabelImportDefaultSpecifier, ImportKind, ImportNamespaceSpecifier, ImportSpecifier as BabelImportSpecifier, ImportSpecifierType, ModuleDeclaration, ModuleExportNameType, TSExportAssignment, TSImportEqualsDeclaration, TSNamespaceExportDeclaration, }; use crate::babelify::{Babelify, Context}; #[derive(Debug, Clone, Serialize, Deserialize)] pub enum ModuleDeclOutput { Import(ImportDeclaration), ExportDefault(ExportDefaultDeclaration), ExportNamed(ExportNamedDeclaration), ExportAll(ExportAllDeclaration), TsImportEquals(TSImportEqualsDeclaration), TsExportAssignment(TSExportAssignment), TsNamespaceExport(TSNamespaceExportDeclaration), } impl Babelify for ModuleDecl { type Output = ModuleDeclOutput; fn babelify(self, ctx: &Context) -> Self::Output { match self { ModuleDecl::Import(i) => ModuleDeclOutput::Import(i.babelify(ctx)), ModuleDecl::ExportDecl(e) => ModuleDeclOutput::ExportNamed(e.babelify(ctx)), ModuleDecl::ExportNamed(n) => ModuleDeclOutput::ExportNamed(n.babelify(ctx)), ModuleDecl::ExportDefaultDecl(e) => ModuleDeclOutput::ExportDefault(e.babelify(ctx)), ModuleDecl::ExportDefaultExpr(e) => ModuleDeclOutput::ExportDefault(e.babelify(ctx)), ModuleDecl::ExportAll(a) => ModuleDeclOutput::ExportAll(a.babelify(ctx)), ModuleDecl::TsImportEquals(i) => ModuleDeclOutput::TsImportEquals(i.babelify(ctx)), ModuleDecl::TsExportAssignment(a) => { ModuleDeclOutput::TsExportAssignment(a.babelify(ctx)) } ModuleDecl::TsNamespaceExport(e) => { ModuleDeclOutput::TsNamespaceExport(e.babelify(ctx)) } } } } impl From<ModuleDeclOutput> for ModuleDeclaration { fn from(module: ModuleDeclOutput) -> Self { match module { ModuleDeclOutput::Import(i) => ModuleDeclaration::Import(i), ModuleDeclOutput::ExportDefault(e) => ModuleDeclaration::ExportDefault(e), ModuleDeclOutput::ExportNamed(n) => ModuleDeclaration::ExportNamed(n), ModuleDeclOutput::ExportAll(a) => ModuleDeclaration::ExportAll(a), _ => panic!( "illegal conversion: Cannot convert {:?} to ModuleDeclaration", &module ), } } } impl Babelify for ExportDefaultExpr { type Output = ExportDefaultDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { ExportDefaultDeclaration { base: ctx.base(self.span), declaration: ExportDefaultDeclType::Expr( Box::alloc().init(self.expr.babelify(ctx).into()), ), } } } impl Babelify for ExportDecl { type Output = ExportNamedDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { ExportNamedDeclaration { base: ctx.base(self.span), declaration: Some(Box::alloc().init(self.decl.babelify(ctx))), specifiers: Default::default(), source: Default::default(), with: Default::default(), export_kind: Default::default(), } } } fn convert_import_attrs( asserts: Option<Box<ObjectLit>>, ctx: &Context, ) -> Option<Vec<ImportAttribute>> { asserts.map(|obj| { let obj_span = obj.span; obj.props .into_iter() .map(|prop_or_spread| { let prop = match prop_or_spread { PropOrSpread::Prop(p) => p, _ => panic!( "illegal conversion: Cannot convert {:?} to Prop", &prop_or_spread ), }; let (key, val) = match *prop { Prop::KeyValue(keyval) => { let key = match keyval.key { PropName::Ident(i) => IdOrString::Id(i.babelify(ctx)), PropName::Str(s) => IdOrString::String(s.babelify(ctx)), _ => panic!( "illegal conversion: Cannot convert {:?} to Prop::KeyValue", &keyval.key ), }; let val = match *keyval.value { Expr::Lit(lit) => match lit { Lit::Str(s) => s.babelify(ctx), _ => panic!( "illegal conversion: Cannot convert {:?} to Expr::Lit", &lit ), }, _ => panic!( "illegal conversion: Cannot convert {:?} to Expr::Lit", &keyval.value ), }; (key, val) } _ => panic!( "illegal conversion: Cannot convert {:?} to key, value", &prop ), }; ImportAttribute { base: ctx.base(obj_span), key, value: val, } }) .collect() }) } impl Babelify for ImportDecl { type Output = ImportDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { ImportDeclaration { base: ctx.base(self.span), specifiers: self.specifiers.babelify(ctx), source: self.src.babelify(ctx), with: convert_import_attrs(self.with, ctx), import_kind: if self.type_only { Some(ImportKind::Type) } else { None }, phase: self.phase.babelify(ctx), } } } impl Babelify for swc_ecma_ast::ImportPhase { type Output = Option<swc_estree_ast::ImportPhase>; fn babelify(self, _: &Context) -> Self::Output { match self { Self::Evaluation => None, Self::Source => Some(swc_estree_ast::ImportPhase::Source), Self::Defer => Some(swc_estree_ast::ImportPhase::Defer), } } } impl Babelify for ExportAll { type Output = ExportAllDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { ExportAllDeclaration { base: ctx.base(self.span), source: self.src.babelify(ctx), with: convert_import_attrs(self.with, ctx), export_kind: if self.type_only { Some(ExportKind::Type) } else { None }, } } } impl Babelify for NamedExport { type Output = ExportNamedDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { ExportNamedDeclaration { base: ctx.base(self.span), declaration: Default::default(), specifiers: self.specifiers.babelify(ctx), source: self.src.map(|s| s.babelify(ctx)), with: convert_import_attrs(self.with, ctx), export_kind: if self.type_only { Some(ExportKind::Type) } else { None }, } } } impl Babelify for ExportDefaultDecl { type Output = ExportDefaultDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { ExportDefaultDeclaration { base: ctx.base(self.span), declaration: self.decl.babelify(ctx), } } } impl Babelify for DefaultDecl { type Output = ExportDefaultDeclType; fn babelify(self, ctx: &Context) -> Self::Output { match self { DefaultDecl::Class(c) => ExportDefaultDeclType::Class(c.babelify(ctx).into()), DefaultDecl::Fn(f) => ExportDefaultDeclType::Func(f.babelify(ctx).into()), DefaultDecl::TsInterfaceDecl(_) => panic!("unimplemented"), /* TODO(dwoznicki): Babel expects a TSDeclareFunction here, which does not map cleanly to TsInterfaceDecl expected by swc */ } } } impl Babelify for ImportSpecifier { type Output = ImportSpecifierType; fn babelify(self, ctx: &Context) -> Self::Output { match self { ImportSpecifier::Named(s) => ImportSpecifierType::Import(s.babelify(ctx)), ImportSpecifier::Default(s) => ImportSpecifierType::Default(s.babelify(ctx)), ImportSpecifier::Namespace(s) => ImportSpecifierType::Namespace(s.babelify(ctx)), } } } impl Babelify for ImportDefaultSpecifier { type Output = BabelImportDefaultSpecifier; fn babelify(self, ctx: &Context) -> Self::Output { BabelImportDefaultSpecifier { base: ctx.base(self.span), local: self.local.babelify(ctx), } } } impl Babelify for ImportStarAsSpecifier { type Output = ImportNamespaceSpecifier; fn babelify(self, ctx: &Context) -> Self::Output { ImportNamespaceSpecifier { base: ctx.base(self.span), local: self.local.babelify(ctx), } } } impl Babelify for ImportNamedSpecifier { type Output = BabelImportSpecifier; fn babelify(self, ctx: &Context) -> Self::Output { BabelImportSpecifier { base: ctx.base(self.span), local: self.local.clone().babelify(ctx), imported: self .imported .unwrap_or(ModuleExportName::Ident(self.local)) .babelify(ctx), import_kind: if self.is_type_only { Some(ImportKind::Type) } else { None }, } } } impl Babelify for ExportSpecifier { type Output = ExportSpecifierType; fn babelify(self, ctx: &Context) -> Self::Output { match self { ExportSpecifier::Named(s) => ExportSpecifierType::Export(s.babelify(ctx)), ExportSpecifier::Default(s) => ExportSpecifierType::Default(s.babelify(ctx)), ExportSpecifier::Namespace(s) => ExportSpecifierType::Namespace(s.babelify(ctx)), } } } impl Babelify for ExportNamespaceSpecifier { type Output = BabelExportNamespaceSpecifier; fn babelify(self, ctx: &Context) -> Self::Output { BabelExportNamespaceSpecifier { base: ctx.base(self.span), exported: self.name.babelify(ctx), } } } impl Babelify for ExportDefaultSpecifier { type Output = BabelExportDefaultSpecifier; fn babelify(self, ctx: &Context) -> Self::Output { let exported = self.exported.babelify(ctx); BabelExportDefaultSpecifier { base: exported.base.clone(), exported, } } } impl Babelify for ExportNamedSpecifier { type Output = BabelExportSpecifier; fn babelify(self, ctx: &Context) -> Self::Output { BabelExportSpecifier { base: ctx.base(self.span), local: self.orig.clone().babelify(ctx), exported: self.exported.unwrap_or(self.orig).babelify(ctx), export_kind: if self.is_type_only { ExportKind::Type } else { ExportKind::Value }, } } } impl Babelify for ModuleExportName { type Output = ModuleExportNameType; fn babelify(self, ctx: &Context) -> Self::Output { match self { ModuleExportName::Ident(ident) => ModuleExportNameType::Ident(ident.babelify(ctx)), ModuleExportName::Str(..) => unimplemented!("module string names unimplemented"), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/babelify/operators.rs
Rust
use serde::{Deserialize, Serialize}; use swc_ecma_ast::{AssignOp, BinaryOp, UnaryOp, UpdateOp}; use swc_estree_ast::{BinaryExprOp, LogicalExprOp, UnaryExprOp, UpdateExprOp}; use crate::babelify::{Babelify, Context}; #[derive(Debug, Clone, Serialize, Deserialize)] pub enum BinaryOpOutput { BinOp(BinaryExprOp), LogicOp(LogicalExprOp), } impl From<BinaryOpOutput> for BinaryExprOp { fn from(o: BinaryOpOutput) -> Self { match o { BinaryOpOutput::BinOp(op) => op, BinaryOpOutput::LogicOp(_) => panic!( "illegal conversion: Cannot convert {:?} to BinaryExprOp", &o ), } } } impl From<BinaryOpOutput> for LogicalExprOp { fn from(o: BinaryOpOutput) -> Self { match o { BinaryOpOutput::LogicOp(op) => op, BinaryOpOutput::BinOp(_) => panic!( "illegal conversion: Cannot convert {:?} to LogicalExprOp", &o ), } } } impl Babelify for BinaryOp { type Output = BinaryOpOutput; fn babelify(self, _ctx: &Context) -> Self::Output { match self { BinaryOp::EqEq => BinaryOpOutput::BinOp(BinaryExprOp::Equal), BinaryOp::NotEq => BinaryOpOutput::BinOp(BinaryExprOp::NotEqual), BinaryOp::EqEqEq => BinaryOpOutput::BinOp(BinaryExprOp::StrictEqual), BinaryOp::NotEqEq => BinaryOpOutput::BinOp(BinaryExprOp::StrictNotEqual), BinaryOp::Lt => BinaryOpOutput::BinOp(BinaryExprOp::LessThan), BinaryOp::LtEq => BinaryOpOutput::BinOp(BinaryExprOp::LessThanOrEqual), BinaryOp::Gt => BinaryOpOutput::BinOp(BinaryExprOp::GreaterThan), BinaryOp::GtEq => BinaryOpOutput::BinOp(BinaryExprOp::GreaterThanOrEqual), BinaryOp::LShift => BinaryOpOutput::BinOp(BinaryExprOp::LeftShift), BinaryOp::RShift => BinaryOpOutput::BinOp(BinaryExprOp::RightShift), BinaryOp::ZeroFillRShift => BinaryOpOutput::BinOp(BinaryExprOp::UnsignedRightShift), BinaryOp::Add => BinaryOpOutput::BinOp(BinaryExprOp::Addition), BinaryOp::Sub => BinaryOpOutput::BinOp(BinaryExprOp::Subtraction), BinaryOp::Mul => BinaryOpOutput::BinOp(BinaryExprOp::Multiplication), BinaryOp::Div => BinaryOpOutput::BinOp(BinaryExprOp::Division), BinaryOp::Mod => BinaryOpOutput::BinOp(BinaryExprOp::Remainder), BinaryOp::BitOr => BinaryOpOutput::BinOp(BinaryExprOp::Or), BinaryOp::BitXor => BinaryOpOutput::BinOp(BinaryExprOp::Xor), BinaryOp::BitAnd => BinaryOpOutput::BinOp(BinaryExprOp::And), BinaryOp::LogicalOr => BinaryOpOutput::LogicOp(LogicalExprOp::Or), BinaryOp::LogicalAnd => BinaryOpOutput::LogicOp(LogicalExprOp::And), BinaryOp::In => BinaryOpOutput::BinOp(BinaryExprOp::In), BinaryOp::InstanceOf => BinaryOpOutput::BinOp(BinaryExprOp::Instanceof), BinaryOp::Exp => BinaryOpOutput::BinOp(BinaryExprOp::Exponentiation), BinaryOp::NullishCoalescing => BinaryOpOutput::LogicOp(LogicalExprOp::Nullish), } } } // Babel appears to just store all of these as a string. See // AssignmentExpression.operator field. NOTE(dwoznick): I'm unsure if this is // the correct way to handle this case. impl Babelify for AssignOp { type Output = String; fn babelify(self, _ctx: &Context) -> Self::Output { match self { AssignOp::Assign => "=".into(), AssignOp::AddAssign => "+=".into(), AssignOp::SubAssign => "-=".into(), AssignOp::MulAssign => "*=".into(), AssignOp::DivAssign => "/=".into(), AssignOp::ModAssign => "%=".into(), AssignOp::LShiftAssign => "<<=".into(), AssignOp::RShiftAssign => ">>=".into(), AssignOp::ZeroFillRShiftAssign => ">>>=".into(), AssignOp::BitOrAssign => "|=".into(), AssignOp::BitXorAssign => "^=".into(), AssignOp::BitAndAssign => "&=".into(), AssignOp::ExpAssign => "**=".into(), AssignOp::AndAssign => "&&=".into(), AssignOp::OrAssign => "||=".into(), AssignOp::NullishAssign => "??=".into(), } } } impl Babelify for UpdateOp { type Output = UpdateExprOp; fn babelify(self, _ctx: &Context) -> Self::Output { match self { UpdateOp::PlusPlus => UpdateExprOp::Increment, UpdateOp::MinusMinus => UpdateExprOp::Decrement, } } } impl Babelify for UnaryOp { type Output = UnaryExprOp; fn babelify(self, _ctx: &Context) -> Self::Output { match self { // TODO(dwoznicki): missing `throw` op UnaryOp::Minus => UnaryExprOp::Negation, UnaryOp::Plus => UnaryExprOp::Plus, UnaryOp::Bang => UnaryExprOp::LogicalNot, UnaryOp::Tilde => UnaryExprOp::BitwiseNot, UnaryOp::TypeOf => UnaryExprOp::Typeof, UnaryOp::Void => UnaryExprOp::Void, UnaryOp::Delete => UnaryExprOp::Delete, } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/babelify/pat.rs
Rust
use copyless::BoxHelper; use serde::{Deserialize, Serialize}; use swc_common::Spanned; use swc_ecma_ast::{ ArrayPat, AssignPat, AssignPatProp, KeyValuePatProp, ObjectPat, ObjectPatProp, Pat, RestPat, }; use swc_estree_ast::{ ArrayPattern, AssignmentPattern, AssignmentPatternLeft, CatchClauseParam, Expression, Identifier, LVal, ObjectKey, ObjectPattern, ObjectPatternProp, ObjectPropVal, ObjectProperty, Param, Pattern, PatternLike, RestElement, }; use crate::babelify::{Babelify, Context}; #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PatOutput { Id(Identifier), Array(ArrayPattern), Rest(RestElement), Object(ObjectPattern), Assign(AssignmentPattern), Expr(Box<Expression>), } impl Babelify for Pat { type Output = PatOutput; fn babelify(self, ctx: &Context) -> Self::Output { match self { Pat::Ident(i) => PatOutput::Id(i.babelify(ctx)), Pat::Array(a) => PatOutput::Array(a.babelify(ctx)), Pat::Rest(r) => PatOutput::Rest(r.babelify(ctx)), Pat::Object(o) => PatOutput::Object(o.babelify(ctx)), Pat::Assign(a) => PatOutput::Assign(a.babelify(ctx)), Pat::Expr(e) => PatOutput::Expr(Box::alloc().init(e.babelify(ctx).into())), Pat::Invalid(_) => panic!( "illegal conversion: Cannot convert {:?} to PatOutput", &self ), } } } impl From<PatOutput> for Pattern { fn from(pat: PatOutput) -> Self { match pat { PatOutput::Assign(a) => Pattern::Assignment(a), PatOutput::Array(a) => Pattern::Array(a), PatOutput::Object(o) => Pattern::Object(o), _ => panic!("illegal conversion: Cannot convert {:?} to Pattern", &pat), } } } impl From<PatOutput> for ObjectPropVal { fn from(pat: PatOutput) -> Self { match pat { PatOutput::Expr(e) => ObjectPropVal::Expr(e), PatOutput::Id(p) => ObjectPropVal::Pattern(PatternLike::Id(p)), PatOutput::Array(p) => ObjectPropVal::Pattern(PatternLike::ArrayPat(p)), PatOutput::Rest(p) => ObjectPropVal::Pattern(PatternLike::RestEl(p)), PatOutput::Object(p) => ObjectPropVal::Pattern(PatternLike::ObjectPat(p)), PatOutput::Assign(p) => ObjectPropVal::Pattern(PatternLike::AssignmentPat(p)), } } } impl From<PatOutput> for LVal { fn from(pat: PatOutput) -> Self { match pat { PatOutput::Id(i) => LVal::Id(i), PatOutput::Array(a) => LVal::ArrayPat(a), PatOutput::Rest(r) => LVal::RestEl(r), PatOutput::Object(o) => LVal::ObjectPat(o), PatOutput::Assign(a) => LVal::AssignmentPat(a), PatOutput::Expr(expr) => match *expr { Expression::Member(e) => LVal::MemberExpr(e), _ => panic!("illegal conversion: Cannot convert {:?} to LVal", &expr), }, } } } impl From<PatOutput> for PatternLike { fn from(pat: PatOutput) -> Self { match pat { PatOutput::Id(i) => PatternLike::Id(i), PatOutput::Array(a) => PatternLike::ArrayPat(a), PatOutput::Rest(r) => PatternLike::RestEl(r), PatOutput::Object(o) => PatternLike::ObjectPat(o), PatOutput::Assign(a) => PatternLike::AssignmentPat(a), PatOutput::Expr(_) => panic!("illegal conversion: Cannot convert {:?} to LVal", &pat), } } } impl From<PatOutput> for AssignmentPatternLeft { fn from(pat: PatOutput) -> Self { match pat { PatOutput::Id(i) => AssignmentPatternLeft::Id(i), PatOutput::Array(a) => AssignmentPatternLeft::Array(a), PatOutput::Object(o) => AssignmentPatternLeft::Object(o), PatOutput::Expr(expr) => match *expr { Expression::Member(e) => AssignmentPatternLeft::Member(e), _ => panic!( "illegal conversion: Cannot convert {:?} to AssignmentPatternLeft", &expr ), }, PatOutput::Rest(_) => panic!( "illegal conversion: Cannot convert {:?} to AssignmentPatternLeft", &pat ), PatOutput::Assign(_) => panic!( "illegal conversion: Cannot convert {:?} to AssignmentPatternLeft", &pat ), } } } impl From<PatOutput> for Param { fn from(pat: PatOutput) -> Self { match pat { PatOutput::Id(i) => Param::Id(i), PatOutput::Rest(r) => Param::Rest(r), PatOutput::Array(p) => Param::Pat(Pattern::Array(p)), PatOutput::Object(p) => Param::Pat(Pattern::Object(p)), PatOutput::Assign(p) => Param::Pat(Pattern::Assignment(p)), PatOutput::Expr(p) => panic!("Cannot convert {:?} to Param", p), } } } impl From<PatOutput> for CatchClauseParam { fn from(pat: PatOutput) -> Self { match pat { PatOutput::Id(i) => CatchClauseParam::Id(i), PatOutput::Array(a) => CatchClauseParam::Array(a), PatOutput::Object(o) => CatchClauseParam::Object(o), _ => panic!( "illegal conversion: Cannot convert {:?} to CatchClauseParam", &pat ), } } } impl Babelify for ArrayPat { type Output = ArrayPattern; fn babelify(self, ctx: &Context) -> Self::Output { ArrayPattern { base: ctx.base(self.span), elements: self .elems .into_iter() .map(|opt| opt.map(|e| e.babelify(ctx).into())) .collect(), type_annotation: self .type_ann .map(|a| Box::alloc().init(a.babelify(ctx).into())), decorators: Default::default(), } } } impl Babelify for ObjectPat { type Output = ObjectPattern; fn babelify(self, ctx: &Context) -> Self::Output { ObjectPattern { base: ctx.base(self.span), properties: self.props.babelify(ctx), type_annotation: self .type_ann .map(|a| Box::alloc().init(a.babelify(ctx).into())), decorators: Default::default(), } } } impl Babelify for ObjectPatProp { type Output = ObjectPatternProp; fn babelify(self, ctx: &Context) -> Self::Output { match self { ObjectPatProp::KeyValue(p) => ObjectPatternProp::Prop(p.babelify(ctx)), ObjectPatProp::Rest(r) => ObjectPatternProp::Rest(r.babelify(ctx)), ObjectPatProp::Assign(a) => ObjectPatternProp::Prop(a.babelify(ctx)), } } } impl Babelify for KeyValuePatProp { type Output = ObjectProperty; fn babelify(self, ctx: &Context) -> Self::Output { ObjectProperty { base: ctx.base(self.span()), key: self.key.babelify(ctx), value: self.value.babelify(ctx).into(), computed: Default::default(), shorthand: Default::default(), decorators: Default::default(), } } } impl Babelify for RestPat { type Output = RestElement; fn babelify(self, ctx: &Context) -> Self::Output { RestElement { base: ctx.base(self.span), argument: Box::alloc().init(self.arg.babelify(ctx).into()), type_annotation: self .type_ann .map(|a| Box::alloc().init(a.babelify(ctx).into())), decorators: Default::default(), } } } impl Babelify for AssignPat { type Output = AssignmentPattern; fn babelify(self, ctx: &Context) -> Self::Output { AssignmentPattern { base: ctx.base(self.span), left: self.left.babelify(ctx).into(), right: Box::alloc().init(self.right.babelify(ctx).into()), type_annotation: None, decorators: Default::default(), } } } impl Babelify for AssignPatProp { type Output = ObjectProperty; fn babelify(self, ctx: &Context) -> Self::Output { let is_shorthand = self.value.is_none(); ObjectProperty { base: ctx.base(self.span), key: ObjectKey::Id(self.key.clone().babelify(ctx)), value: if is_shorthand { ObjectPropVal::Pattern(PatternLike::Id(self.key.babelify(ctx))) } else { ObjectPropVal::Expr(Box::alloc().init(self.value.unwrap().babelify(ctx).into())) }, shorthand: is_shorthand, computed: Default::default(), decorators: Default::default(), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/babelify/prop.rs
Rust
use copyless::BoxHelper; use swc_common::Spanned; use swc_ecma_ast::{ AssignProp, ComputedPropName, GetterProp, KeyValueProp, MethodProp, Prop, PropName, SetterProp, }; use swc_estree_ast::{ AssignmentPattern, AssignmentPatternLeft, Expression, FunctionExpression, ObjectKey, ObjectMember, ObjectMethod, ObjectMethodKind, ObjectPropVal, ObjectProperty, }; use crate::babelify::{Babelify, Context}; impl Babelify for Prop { type Output = ObjectMember; fn babelify(self, ctx: &Context) -> Self::Output { match self { Prop::Shorthand(i) => { let id = i.babelify(ctx); ObjectMember::Prop(ObjectProperty { base: id.base.clone(), key: ObjectKey::Id(id.clone()), value: ObjectPropVal::Expr(Box::alloc().init(Expression::Id(id))), computed: Default::default(), shorthand: true, decorators: Default::default(), }) } Prop::KeyValue(k) => ObjectMember::Prop(k.babelify(ctx)), Prop::Getter(g) => ObjectMember::Method(g.babelify(ctx)), Prop::Setter(s) => ObjectMember::Method(s.babelify(ctx)), Prop::Method(m) => ObjectMember::Method(m.babelify(ctx)), _ => panic!( "illegal conversion: Cannot convert {:?} to ObjectMember", &self ), } } } impl Babelify for KeyValueProp { type Output = ObjectProperty; fn babelify(self, ctx: &Context) -> Self::Output { ObjectProperty { base: ctx.base(self.span()), key: self.key.babelify(ctx), value: ObjectPropVal::Expr(Box::alloc().init(self.value.babelify(ctx).into())), computed: Default::default(), shorthand: Default::default(), decorators: Default::default(), } } } // TODO(dwoznicki): What is AssignProp used for? Should it babelify into // AssignmentPattern or AssignmentExpression? impl Babelify for AssignProp { type Output = AssignmentPattern; fn babelify(self, ctx: &Context) -> Self::Output { AssignmentPattern { base: ctx.base(self.span()), left: AssignmentPatternLeft::Id(self.key.babelify(ctx)), right: Box::alloc().init(self.value.babelify(ctx).into()), decorators: Default::default(), type_annotation: Default::default(), } } } impl Babelify for GetterProp { type Output = ObjectMethod; fn babelify(self, ctx: &Context) -> Self::Output { ObjectMethod { base: ctx.base(self.span), kind: ObjectMethodKind::Get, key: self.key.babelify(ctx), return_type: self .type_ann .map(|ann| Box::alloc().init(ann.babelify(ctx).into())), body: self.body.unwrap().babelify(ctx), params: Default::default(), computed: Default::default(), generator: Default::default(), is_async: Default::default(), decorator: Default::default(), type_parameters: Default::default(), } } } impl Babelify for SetterProp { type Output = ObjectMethod; fn babelify(self, ctx: &Context) -> Self::Output { ObjectMethod { base: ctx.base(self.span), kind: ObjectMethodKind::Set, key: self.key.babelify(ctx), params: vec![self.param.babelify(ctx).into()], body: self.body.unwrap().babelify(ctx), return_type: Default::default(), computed: Default::default(), generator: Default::default(), is_async: Default::default(), decorator: Default::default(), type_parameters: Default::default(), } } } impl Babelify for MethodProp { type Output = ObjectMethod; fn babelify(self, ctx: &Context) -> Self::Output { let func: FunctionExpression = self.function.babelify(ctx); ObjectMethod { base: func.base, kind: ObjectMethodKind::Method, key: self.key.babelify(ctx), params: func.params, body: func.body, computed: Default::default(), generator: func.generator, is_async: func.is_async, decorator: Default::default(), return_type: func.return_type, type_parameters: func.type_parameters, } } } impl Babelify for PropName { type Output = ObjectKey; fn babelify(self, ctx: &Context) -> Self::Output { match self { PropName::Ident(i) => ObjectKey::Id(i.babelify(ctx)), PropName::Str(s) => ObjectKey::String(s.babelify(ctx)), PropName::Num(n) => ObjectKey::Numeric(n.babelify(ctx)), PropName::Computed(e) => ObjectKey::Expr(Box::alloc().init(e.babelify(ctx))), _ => panic!( "illegal conversion: Cannot convert {:?} to ObjectKey", &self ), } } } impl Babelify for ComputedPropName { type Output = Expression; fn babelify(self, ctx: &Context) -> Self::Output { self.expr.babelify(ctx).into() } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/babelify/stmt.rs
Rust
use copyless::BoxHelper; use swc_ecma_ast::{ BlockStmt, BreakStmt, CatchClause, ContinueStmt, DebuggerStmt, Decl, DoWhileStmt, EmptyStmt, ExprStmt, ForHead, ForInStmt, ForOfStmt, ForStmt, IfStmt, LabeledStmt, ReturnStmt, Stmt, SwitchCase, SwitchStmt, ThrowStmt, TryStmt, VarDeclOrExpr, WhileStmt, WithStmt, }; use swc_estree_ast::{ BlockStatement, BreakStatement, CatchClause as BabelCatchClause, ContinueStatement, DebuggerStatement, DoWhileStatement, EmptyStatement, ExpressionStatement, ForInStatement, ForOfStatement, ForStatement, ForStmtInit, ForStmtLeft, IfStatement, LabeledStatement, ReturnStatement, Statement, SwitchCase as BabelSwitchCase, SwitchStatement, ThrowStatement, TryStatement, WhileStatement, WithStatement, }; use crate::babelify::{Babelify, Context}; impl Babelify for BlockStmt { type Output = BlockStatement; fn babelify(self, ctx: &Context) -> Self::Output { BlockStatement { base: ctx.base(self.span), body: self.stmts.babelify(ctx), directives: Default::default(), } } } impl Babelify for Stmt { type Output = Statement; fn parallel(cnt: usize) -> bool { cnt >= 16 } fn babelify(self, ctx: &Context) -> Self::Output { match self { Stmt::Block(s) => Statement::Block(s.babelify(ctx)), Stmt::Empty(s) => Statement::Empty(s.babelify(ctx)), Stmt::Debugger(s) => Statement::Debugger(s.babelify(ctx)), Stmt::With(s) => Statement::With(s.babelify(ctx)), Stmt::Return(s) => Statement::Return(s.babelify(ctx)), Stmt::Labeled(s) => Statement::Labeled(s.babelify(ctx)), Stmt::Break(s) => Statement::Break(s.babelify(ctx)), Stmt::Continue(s) => Statement::Continue(s.babelify(ctx)), Stmt::If(s) => Statement::If(s.babelify(ctx)), Stmt::Switch(s) => Statement::Switch(s.babelify(ctx)), Stmt::Throw(s) => Statement::Throw(s.babelify(ctx)), Stmt::Try(s) => Statement::Try(s.babelify(ctx)), Stmt::While(s) => Statement::While(s.babelify(ctx)), Stmt::DoWhile(s) => Statement::DoWhile(s.babelify(ctx)), Stmt::For(s) => Statement::For(s.babelify(ctx)), Stmt::ForIn(s) => Statement::ForIn(s.babelify(ctx)), Stmt::ForOf(s) => Statement::ForOf(s.babelify(ctx)), Stmt::Decl(decl) => match decl { Decl::Class(d) => Statement::ClassDecl(d.babelify(ctx)), Decl::Fn(d) => Statement::FuncDecl(d.babelify(ctx)), Decl::Var(d) => Statement::VarDecl(d.babelify(ctx)), Decl::Using(d) => Statement::UsingDecl(d.babelify(ctx)), Decl::TsInterface(d) => Statement::TSInterfaceDecl(d.babelify(ctx)), Decl::TsTypeAlias(d) => Statement::TSTypeAliasDecl(d.babelify(ctx)), Decl::TsEnum(d) => Statement::TSEnumDecl(d.babelify(ctx)), Decl::TsModule(d) => Statement::TSModuleDecl(d.babelify(ctx)), }, Stmt::Expr(s) => Statement::Expr(s.babelify(ctx)), } } } impl Babelify for ExprStmt { type Output = ExpressionStatement; fn babelify(self, ctx: &Context) -> Self::Output { ExpressionStatement { base: ctx.base(self.span), expression: Box::alloc().init(self.expr.babelify(ctx).into()), } } } impl Babelify for EmptyStmt { type Output = EmptyStatement; fn babelify(self, ctx: &Context) -> Self::Output { EmptyStatement { base: ctx.base(self.span), } } } impl Babelify for DebuggerStmt { type Output = DebuggerStatement; fn babelify(self, ctx: &Context) -> Self::Output { DebuggerStatement { base: ctx.base(self.span), } } } impl Babelify for WithStmt { type Output = WithStatement; fn babelify(self, ctx: &Context) -> Self::Output { WithStatement { base: ctx.base(self.span), object: Box::alloc().init(self.obj.babelify(ctx).into()), body: Box::alloc().init(self.body.babelify(ctx)), } } } impl Babelify for ReturnStmt { type Output = ReturnStatement; fn babelify(self, ctx: &Context) -> Self::Output { ReturnStatement { base: ctx.base(self.span), argument: self .arg .map(|expr| Box::alloc().init(expr.babelify(ctx).into())), } } } impl Babelify for LabeledStmt { type Output = LabeledStatement; fn babelify(self, ctx: &Context) -> Self::Output { LabeledStatement { base: ctx.base(self.span), label: self.label.babelify(ctx), body: Box::alloc().init(self.body.babelify(ctx)), } } } impl Babelify for BreakStmt { type Output = BreakStatement; fn babelify(self, ctx: &Context) -> Self::Output { BreakStatement { base: ctx.base(self.span), label: self.label.map(|id| id.babelify(ctx)), } } } impl Babelify for ContinueStmt { type Output = ContinueStatement; fn babelify(self, ctx: &Context) -> Self::Output { ContinueStatement { base: ctx.base(self.span), label: self.label.map(|id| id.babelify(ctx)), } } } impl Babelify for IfStmt { type Output = IfStatement; fn babelify(self, ctx: &Context) -> Self::Output { IfStatement { base: ctx.base(self.span), test: Box::alloc().init(self.test.babelify(ctx).into()), consequent: Box::alloc().init(self.cons.babelify(ctx)), alternate: self.alt.map(|a| Box::alloc().init(a.babelify(ctx))), } } } impl Babelify for SwitchStmt { type Output = SwitchStatement; fn babelify(self, ctx: &Context) -> Self::Output { SwitchStatement { base: ctx.base(self.span), discriminant: Box::alloc().init(self.discriminant.babelify(ctx).into()), cases: self.cases.babelify(ctx), } } } impl Babelify for ThrowStmt { type Output = ThrowStatement; fn babelify(self, ctx: &Context) -> Self::Output { ThrowStatement { base: ctx.base(self.span), argument: Box::alloc().init(self.arg.babelify(ctx).into()), } } } impl Babelify for TryStmt { type Output = TryStatement; fn babelify(self, ctx: &Context) -> Self::Output { TryStatement { base: ctx.base(self.span), block: self.block.babelify(ctx), handler: self.handler.map(|clause| clause.babelify(ctx)), finalizer: self.finalizer.map(|stmt| stmt.babelify(ctx)), } } } impl Babelify for WhileStmt { type Output = WhileStatement; fn babelify(self, ctx: &Context) -> Self::Output { WhileStatement { base: ctx.base(self.span), test: Box::alloc().init(self.test.babelify(ctx).into()), body: Box::alloc().init(self.body.babelify(ctx)), } } } impl Babelify for DoWhileStmt { type Output = DoWhileStatement; fn babelify(self, ctx: &Context) -> Self::Output { DoWhileStatement { base: ctx.base(self.span), test: Box::alloc().init(self.test.babelify(ctx).into()), body: Box::alloc().init(self.body.babelify(ctx)), } } } impl Babelify for ForStmt { type Output = ForStatement; fn babelify(self, ctx: &Context) -> Self::Output { ForStatement { base: ctx.base(self.span), init: self.init.map(|i| i.babelify(ctx)), test: self .test .map(|expr| Box::alloc().init(expr.babelify(ctx).into())), update: self .update .map(|expr| Box::alloc().init(expr.babelify(ctx).into())), body: Box::alloc().init(self.body.babelify(ctx)), } } } impl Babelify for ForInStmt { type Output = ForInStatement; fn babelify(self, ctx: &Context) -> Self::Output { ForInStatement { base: ctx.base(self.span), left: self.left.babelify(ctx), right: Box::alloc().init(self.right.babelify(ctx).into()), body: Box::alloc().init(self.body.babelify(ctx)), } } } impl Babelify for ForOfStmt { type Output = ForOfStatement; fn babelify(self, ctx: &Context) -> Self::Output { ForOfStatement { base: ctx.base(self.span), left: self.left.babelify(ctx), right: Box::alloc().init(self.right.babelify(ctx).into()), body: Box::alloc().init(self.body.babelify(ctx)), // await_token not yet implemented } } } impl Babelify for SwitchCase { type Output = BabelSwitchCase; fn babelify(self, ctx: &Context) -> Self::Output { BabelSwitchCase { base: ctx.base(self.span), test: self .test .map(|expr| Box::alloc().init(expr.babelify(ctx).into())), consequent: self.cons.babelify(ctx), } } } impl Babelify for CatchClause { type Output = BabelCatchClause; fn babelify(self, ctx: &Context) -> Self::Output { BabelCatchClause { base: ctx.base(self.span), param: self.param.map(|p| p.babelify(ctx).into()), body: self.body.babelify(ctx), } } } impl Babelify for ForHead { type Output = ForStmtLeft; fn babelify(self, ctx: &Context) -> Self::Output { match self { ForHead::VarDecl(v) => ForStmtLeft::VarDecl(v.babelify(ctx)), ForHead::Pat(p) => ForStmtLeft::LVal(p.babelify(ctx).into()), _ => { todo!("ForHead::UsingDecl({self:?})") } } } } impl Babelify for VarDeclOrExpr { type Output = ForStmtInit; fn babelify(self, ctx: &Context) -> Self::Output { match self { VarDeclOrExpr::VarDecl(v) => ForStmtInit::VarDecl(v.babelify(ctx)), VarDeclOrExpr::Expr(e) => ForStmtInit::Expr(Box::alloc().init(e.babelify(ctx).into())), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/babelify/typescript.rs
Rust
use copyless::BoxHelper; use serde::{Deserialize, Serialize}; use swc_atoms::Atom; use swc_common::Spanned; use swc_ecma_ast::{ Accessibility, Expr, MemberProp, Pat, TruePlusMinus, TsArrayType, TsAsExpr, TsCallSignatureDecl, TsConditionalType, TsConstAssertion, TsConstructSignatureDecl, TsConstructorType, TsEntityName, TsEnumDecl, TsEnumMember, TsEnumMemberId, TsExportAssignment, TsExprWithTypeArgs, TsExternalModuleRef, TsFnOrConstructorType, TsFnParam, TsFnType, TsImportEqualsDecl, TsImportType, TsIndexSignature, TsIndexedAccessType, TsInferType, TsInterfaceBody, TsInterfaceDecl, TsIntersectionType, TsKeywordType, TsKeywordTypeKind, TsLit, TsLitType, TsMappedType, TsMethodSignature, TsModuleBlock, TsModuleDecl, TsModuleName, TsModuleRef, TsNamespaceBody, TsNamespaceDecl, TsNamespaceExportDecl, TsNonNullExpr, TsOptionalType, TsParamProp, TsParamPropParam, TsParenthesizedType, TsPropertySignature, TsQualifiedName, TsRestType, TsThisType, TsThisTypeOrIdent, TsTplLitType, TsTupleElement, TsTupleType, TsType, TsTypeAliasDecl, TsTypeAnn, TsTypeAssertion, TsTypeElement, TsTypeLit, TsTypeOperator, TsTypeOperatorOp, TsTypeParam, TsTypeParamDecl, TsTypeParamInstantiation, TsTypePredicate, TsTypeQuery, TsTypeQueryExpr, TsTypeRef, TsUnionOrIntersectionType, TsUnionType, }; use swc_estree_ast::{ Access, ArrayPattern, IdOrRest, IdOrString, Identifier, ObjectPattern, RestElement, TSAnyKeyword, TSArrayType, TSAsExpression, TSBigIntKeyword, TSBooleanKeyword, TSCallSignatureDeclaration, TSConditionalType, TSConstructSignatureDeclaration, TSConstructorType, TSEntityName, TSEnumDeclaration, TSEnumMember, TSExportAssignment, TSExpressionWithTypeArguments, TSExternalModuleReference, TSFunctionType, TSImportEqualsDeclModuleRef, TSImportEqualsDeclaration, TSImportType, TSIndexSignature, TSIndexedAccessType, TSInferType, TSInterfaceBody, TSInterfaceDeclaration, TSIntersectionType, TSIntrinsicKeyword, TSLiteralType, TSLiteralTypeLiteral, TSMappedType, TSMethodSignature, TSModuleBlock, TSModuleDeclBody, TSModuleDeclaration, TSNamedTupleMember, TSNamespaceExportDeclaration, TSNeverKeyword, TSNonNullExpression, TSNullKeyword, TSNumberKeyword, TSObjectKeyword, TSOptionalType, TSParamPropParam, TSParameterProperty, TSParenthesizedType, TSPropertySignature, TSQualifiedName, TSRestType, TSStringKeyword, TSSymbolKeyword, TSThisType, TSTupleType, TSTupleTypeElType, TSType, TSTypeAliasDeclaration, TSTypeAnnotation, TSTypeAssertion, TSTypeElement, TSTypeLiteral, TSTypeOperator, TSTypeParameter, TSTypeParameterDeclaration, TSTypeParameterInstantiation, TSTypePredicate, TSTypePredicateParamName, TSTypeQuery, TSTypeQueryExprName, TSTypeReference, TSUndefinedKeyword, TSUnionType, TSUnknownKeyword, TSVoidKeyword, }; use crate::babelify::{Babelify, Context}; impl Babelify for TsTypeAnn { type Output = TSTypeAnnotation; fn babelify(self, ctx: &Context) -> Self::Output { TSTypeAnnotation { base: ctx.base(self.span), type_annotation: self.type_ann.babelify(ctx), } } } impl Babelify for TsFnType { type Output = TSFunctionType; fn babelify(self, ctx: &Context) -> Self::Output { TSFunctionType { base: ctx.base(self.span), parameters: self .params .into_iter() .map(|p| p.babelify(ctx).into()) .collect(), type_parameters: self.type_params.babelify(ctx).map(From::from), type_annotation: Some(Box::alloc().init(self.type_ann.babelify(ctx))), } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum TsFnParamOutput { Id(Identifier), Array(ArrayPattern), Rest(RestElement), Object(ObjectPattern), } impl Babelify for TsFnParam { type Output = TsFnParamOutput; fn babelify(self, ctx: &Context) -> Self::Output { match self { TsFnParam::Ident(i) => TsFnParamOutput::Id(i.babelify(ctx)), TsFnParam::Array(a) => TsFnParamOutput::Array(a.babelify(ctx)), TsFnParam::Rest(r) => TsFnParamOutput::Rest(r.babelify(ctx)), TsFnParam::Object(o) => TsFnParamOutput::Object(o.babelify(ctx)), } } } impl From<TsFnParamOutput> for IdOrRest { fn from(o: TsFnParamOutput) -> Self { match o { TsFnParamOutput::Id(i) => IdOrRest::Id(i), TsFnParamOutput::Rest(r) => IdOrRest::Rest(r), _ => panic!("illegal conversion: Cannot convert {:?} to IdOrRest", &o), } } } impl From<TsFnParamOutput> for Identifier { fn from(o: TsFnParamOutput) -> Self { match o { TsFnParamOutput::Id(i) => i, _ => panic!("illegal conversion: Cannot convert {:?} to Identifier", &o), } } } impl Babelify for TsTypeParamDecl { type Output = TSTypeParameterDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { TSTypeParameterDeclaration { base: ctx.base(self.span), params: self.params.babelify(ctx), } } } impl Babelify for TsTypeParam { type Output = TSTypeParameter; fn babelify(self, ctx: &Context) -> Self::Output { TSTypeParameter { base: ctx.base(self.span), name: self.name.sym, is_in: self.is_in, is_out: self.is_out, is_const: self.is_const, constraint: self.constraint.map(|c| Box::alloc().init(c.babelify(ctx))), default: self.default.map(|d| Box::alloc().init(d.babelify(ctx))), } } } impl Babelify for TsTypeParamInstantiation { type Output = TSTypeParameterInstantiation; fn babelify(self, ctx: &Context) -> Self::Output { TSTypeParameterInstantiation { base: ctx.base(self.span), params: self.params.into_iter().map(|v| v.babelify(ctx)).collect(), } } } impl Babelify for TsParamProp { type Output = TSParameterProperty; fn babelify(self, ctx: &Context) -> Self::Output { TSParameterProperty { base: ctx.base(self.span), parameter: self.param.babelify(ctx), accessibility: self.accessibility.map(|access| access.babelify(ctx)), readonly: Some(self.readonly), } } } impl Babelify for TsParamPropParam { type Output = TSParamPropParam; fn babelify(self, ctx: &Context) -> Self::Output { match self { TsParamPropParam::Ident(i) => TSParamPropParam::Id(i.babelify(ctx)), TsParamPropParam::Assign(a) => TSParamPropParam::Assignment(a.babelify(ctx)), } } } impl Babelify for TsQualifiedName { type Output = TSQualifiedName; fn babelify(self, ctx: &Context) -> Self::Output { TSQualifiedName { base: ctx.base(self.span()), left: Box::alloc().init(self.left.babelify(ctx)), right: self.right.babelify(ctx), } } } impl Babelify for TsEntityName { type Output = TSEntityName; fn babelify(self, ctx: &Context) -> Self::Output { match self { TsEntityName::TsQualifiedName(n) => TSEntityName::Qualified(n.babelify(ctx)), TsEntityName::Ident(i) => TSEntityName::Id(i.babelify(ctx)), } } } impl Babelify for TsTypeElement { type Output = TSTypeElement; fn babelify(self, ctx: &Context) -> Self::Output { match self { TsTypeElement::TsCallSignatureDecl(t) => { TSTypeElement::CallSignatureDecl(t.babelify(ctx)) } TsTypeElement::TsConstructSignatureDecl(t) => { TSTypeElement::ConstructSignatureDecl(t.babelify(ctx)) } TsTypeElement::TsPropertySignature(t) => TSTypeElement::PropSignature(t.babelify(ctx)), TsTypeElement::TsMethodSignature(t) => TSTypeElement::MethodSignature(t.babelify(ctx)), TsTypeElement::TsIndexSignature(t) => TSTypeElement::IndexSignature(t.babelify(ctx)), TsTypeElement::TsGetterSignature(_) => panic!("unimplemented"), TsTypeElement::TsSetterSignature(_) => panic!("unimplemented"), } } } impl Babelify for TsCallSignatureDecl { type Output = TSCallSignatureDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { TSCallSignatureDeclaration { base: ctx.base(self.span), type_parameters: self.type_params.map(|t| t.babelify(ctx)), parameters: self .params .into_iter() .map(|param| param.babelify(ctx).into()) .collect(), type_annotation: self .type_ann .map(|ann| Box::alloc().init(ann.babelify(ctx))), } } } impl Babelify for TsConstructSignatureDecl { type Output = TSConstructSignatureDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { TSConstructSignatureDeclaration { base: ctx.base(self.span), type_parameters: self.type_params.map(|t| t.babelify(ctx)), parameters: self .params .into_iter() .map(|param| param.babelify(ctx).into()) .collect(), type_annotation: self .type_ann .map(|ann| Box::alloc().init(ann.babelify(ctx))), } } } impl Babelify for TsPropertySignature { type Output = TSPropertySignature; fn babelify(self, ctx: &Context) -> Self::Output { TSPropertySignature { base: ctx.base(self.span), key: Box::alloc().init(self.key.babelify(ctx).into()), type_annotation: self .type_ann .map(|ann| Box::alloc().init(ann.babelify(ctx))), computed: Some(self.computed), optional: Some(self.optional), readonly: Some(self.readonly), } } } impl Babelify for TsMethodSignature { type Output = TSMethodSignature; fn babelify(self, ctx: &Context) -> Self::Output { TSMethodSignature { base: ctx.base(self.span), key: Box::alloc().init(self.key.babelify(ctx).into()), type_parameters: self.type_params.map(|t| t.babelify(ctx)), parameters: self .params .into_iter() .map(|param| param.babelify(ctx).into()) .collect(), type_annotation: self .type_ann .map(|ann| Box::alloc().init(ann.babelify(ctx))), computed: Some(self.computed), optional: Some(self.optional), } } } impl Babelify for TsIndexSignature { type Output = TSIndexSignature; fn babelify(self, ctx: &Context) -> Self::Output { TSIndexSignature { base: ctx.base(self.span), parameters: self .params .into_iter() .map(|param| param.babelify(ctx).into()) .collect(), type_annotation: self .type_ann .map(|ann| Box::alloc().init(ann.babelify(ctx))), readonly: Some(self.readonly), } } } impl Babelify for TsType { type Output = TSType; fn babelify(self, ctx: &Context) -> Self::Output { match self { TsType::TsKeywordType(t) => match t.babelify(ctx) { TsKeywordTypeOutput::Any(a) => TSType::AnyKeyword(a), TsKeywordTypeOutput::Unknown(u) => TSType::UnknownKeyword(u), TsKeywordTypeOutput::Number(n) => TSType::NumberKeyword(n), TsKeywordTypeOutput::Object(o) => TSType::ObjectKeyword(o), TsKeywordTypeOutput::Boolean(b) => TSType::BooleanKeyword(b), TsKeywordTypeOutput::BigInt(i) => TSType::BigIntKeyword(i), TsKeywordTypeOutput::String(s) => TSType::StringKeyword(s), TsKeywordTypeOutput::Symbol(s) => TSType::SymbolKeyword(s), TsKeywordTypeOutput::Void(v) => TSType::VoidKeyword(v), TsKeywordTypeOutput::Undefined(u) => TSType::UndefinedKeyword(u), TsKeywordTypeOutput::Null(n) => TSType::NullKeyword(n), TsKeywordTypeOutput::Never(n) => TSType::NeverKeyword(n), TsKeywordTypeOutput::Intrinsic(i) => TSType::IntrinsicKeyword(i), }, TsType::TsThisType(t) => TSType::This(t.babelify(ctx)), TsType::TsFnOrConstructorType(t) => match t.babelify(ctx) { TsFnOrConstructorTypeOutput::Func(f) => TSType::Function(f), TsFnOrConstructorTypeOutput::Constructor(c) => TSType::Constructor(c), }, TsType::TsTypeRef(r) => TSType::TypeRef(r.babelify(ctx)), TsType::TsTypeQuery(q) => TSType::TypeQuery(q.babelify(ctx)), TsType::TsTypeLit(l) => TSType::TypeLiteral(l.babelify(ctx)), TsType::TsArrayType(a) => TSType::Array(a.babelify(ctx)), TsType::TsTupleType(t) => TSType::Tuple(t.babelify(ctx)), TsType::TsOptionalType(o) => TSType::Optional(o.babelify(ctx)), TsType::TsRestType(r) => TSType::Rest(r.babelify(ctx)), TsType::TsUnionOrIntersectionType(t) => match t.babelify(ctx) { TsUnionOrIntersectionTypeOutput::Union(u) => TSType::Union(u), TsUnionOrIntersectionTypeOutput::Intersection(i) => TSType::Intersection(i), }, TsType::TsConditionalType(c) => TSType::Conditional(c.babelify(ctx)), TsType::TsInferType(i) => TSType::Infer(i.babelify(ctx)), TsType::TsParenthesizedType(p) => TSType::Parenthesized(p.babelify(ctx)), TsType::TsTypeOperator(o) => TSType::TypeOp(o.babelify(ctx)), TsType::TsIndexedAccessType(a) => TSType::IndexedAccess(a.babelify(ctx)), TsType::TsMappedType(m) => TSType::Mapped(m.babelify(ctx)), TsType::TsLitType(l) => TSType::Literal(l.babelify(ctx)), TsType::TsTypePredicate(p) => TSType::TypePredicate(p.babelify(ctx)), TsType::TsImportType(i) => TSType::Import(i.babelify(ctx)), } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum TsFnOrConstructorTypeOutput { Func(TSFunctionType), Constructor(TSConstructorType), } impl Babelify for TsFnOrConstructorType { type Output = TsFnOrConstructorTypeOutput; fn babelify(self, ctx: &Context) -> Self::Output { match self { TsFnOrConstructorType::TsFnType(t) => { TsFnOrConstructorTypeOutput::Func(t.babelify(ctx)) } TsFnOrConstructorType::TsConstructorType(t) => { TsFnOrConstructorTypeOutput::Constructor(t.babelify(ctx)) } } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum TsKeywordTypeOutput { Any(TSAnyKeyword), Unknown(TSUnknownKeyword), Number(TSNumberKeyword), Object(TSObjectKeyword), Boolean(TSBooleanKeyword), BigInt(TSBigIntKeyword), String(TSStringKeyword), Symbol(TSSymbolKeyword), Void(TSVoidKeyword), Undefined(TSUndefinedKeyword), Null(TSNullKeyword), Never(TSNeverKeyword), Intrinsic(TSIntrinsicKeyword), } impl Babelify for TsKeywordType { type Output = TsKeywordTypeOutput; fn babelify(self, ctx: &Context) -> Self::Output { match self.kind { TsKeywordTypeKind::TsAnyKeyword => TsKeywordTypeOutput::Any(TSAnyKeyword { base: ctx.base(self.span), }), TsKeywordTypeKind::TsUnknownKeyword => TsKeywordTypeOutput::Unknown(TSUnknownKeyword { base: ctx.base(self.span), }), TsKeywordTypeKind::TsNumberKeyword => TsKeywordTypeOutput::Number(TSNumberKeyword { base: ctx.base(self.span), }), TsKeywordTypeKind::TsObjectKeyword => TsKeywordTypeOutput::Object(TSObjectKeyword { base: ctx.base(self.span), }), TsKeywordTypeKind::TsBooleanKeyword => TsKeywordTypeOutput::Boolean(TSBooleanKeyword { base: ctx.base(self.span), }), TsKeywordTypeKind::TsBigIntKeyword => TsKeywordTypeOutput::BigInt(TSBigIntKeyword { base: ctx.base(self.span), }), TsKeywordTypeKind::TsStringKeyword => TsKeywordTypeOutput::String(TSStringKeyword { base: ctx.base(self.span), }), TsKeywordTypeKind::TsSymbolKeyword => TsKeywordTypeOutput::Symbol(TSSymbolKeyword { base: ctx.base(self.span), }), TsKeywordTypeKind::TsVoidKeyword => TsKeywordTypeOutput::Void(TSVoidKeyword { base: ctx.base(self.span), }), TsKeywordTypeKind::TsUndefinedKeyword => { TsKeywordTypeOutput::Undefined(TSUndefinedKeyword { base: ctx.base(self.span), }) } TsKeywordTypeKind::TsNullKeyword => TsKeywordTypeOutput::Null(TSNullKeyword { base: ctx.base(self.span), }), TsKeywordTypeKind::TsNeverKeyword => TsKeywordTypeOutput::Never(TSNeverKeyword { base: ctx.base(self.span), }), TsKeywordTypeKind::TsIntrinsicKeyword => { TsKeywordTypeOutput::Intrinsic(TSIntrinsicKeyword { base: ctx.base(self.span), }) } } } } impl Babelify for TsThisType { type Output = TSThisType; fn babelify(self, ctx: &Context) -> Self::Output { TSThisType { base: ctx.base(self.span), } } } impl Babelify for TsConstructorType { type Output = TSConstructorType; fn babelify(self, ctx: &Context) -> Self::Output { TSConstructorType { base: ctx.base(self.span), parameters: self .params .into_iter() .map(|param| param.babelify(ctx).into()) .collect(), type_parameters: self.type_params.map(|decl| decl.babelify(ctx)), type_annotation: Some(Box::alloc().init(self.type_ann.babelify(ctx))), is_abstract: Some(self.is_abstract), } } } impl Babelify for TsTypeRef { type Output = TSTypeReference; fn babelify(self, ctx: &Context) -> Self::Output { TSTypeReference { base: ctx.base(self.span), type_name: self.type_name.babelify(ctx), type_parameters: self.type_params.map(|t| t.babelify(ctx)), } } } impl Babelify for TsTypePredicate { type Output = TSTypePredicate; fn babelify(self, ctx: &Context) -> Self::Output { TSTypePredicate { base: ctx.base(self.span), parameter_name: self.param_name.babelify(ctx), type_annotation: self .type_ann .map(|ann| Box::alloc().init(ann.babelify(ctx))), asserts: Some(self.asserts), } } } impl Babelify for TsThisTypeOrIdent { type Output = TSTypePredicateParamName; fn babelify(self, ctx: &Context) -> Self::Output { match self { TsThisTypeOrIdent::Ident(i) => TSTypePredicateParamName::Id(i.babelify(ctx)), TsThisTypeOrIdent::TsThisType(t) => TSTypePredicateParamName::This(t.babelify(ctx)), } } } impl Babelify for TsTypeQuery { type Output = TSTypeQuery; fn babelify(self, ctx: &Context) -> Self::Output { TSTypeQuery { base: ctx.base(self.span), expr_name: self.expr_name.babelify(ctx), } } } impl Babelify for TsTypeQueryExpr { type Output = TSTypeQueryExprName; fn babelify(self, ctx: &Context) -> Self::Output { match self { TsTypeQueryExpr::TsEntityName(n) => TSTypeQueryExprName::EntityName(n.babelify(ctx)), TsTypeQueryExpr::Import(i) => TSTypeQueryExprName::ImportType(i.babelify(ctx)), } } } impl Babelify for TsImportType { type Output = TSImportType; fn babelify(self, ctx: &Context) -> Self::Output { TSImportType { base: ctx.base(self.span), argument: self.arg.babelify(ctx), qualifier: self.qualifier.map(|qual| qual.babelify(ctx)), type_parameters: self.type_args.map(|param| param.babelify(ctx)), } } } impl Babelify for TsTypeLit { type Output = TSTypeLiteral; fn babelify(self, ctx: &Context) -> Self::Output { TSTypeLiteral { base: ctx.base(self.span), members: self.members.babelify(ctx), } } } impl Babelify for TsArrayType { type Output = TSArrayType; fn babelify(self, ctx: &Context) -> Self::Output { TSArrayType { base: ctx.base(self.span), element_type: Box::alloc().init(self.elem_type.babelify(ctx)), } } } impl Babelify for TsTupleType { type Output = TSTupleType; fn babelify(self, ctx: &Context) -> Self::Output { TSTupleType { base: ctx.base(self.span), element_types: self.elem_types.babelify(ctx), } } } impl Babelify for TsTupleElement { type Output = TSTupleTypeElType; fn babelify(self, ctx: &Context) -> Self::Output { match self.label { None => TSTupleTypeElType::TSType(self.ty.babelify(ctx)), Some(pat) => TSTupleTypeElType::Member(TSNamedTupleMember { base: ctx.base(self.span), label: match pat { Pat::Ident(id) => id.babelify(ctx), Pat::Rest(rest) => match *rest.arg { Pat::Ident(id) => id.babelify(ctx), _ => panic!( "illegal conversion: Cannot convert {:?} to Identifier", &rest.arg ), }, _ => panic!( "illegal conversion: Cannot convert {:?} to Identifier", &pat ), }, element_type: self.ty.babelify(ctx), optional: Default::default(), }), } } } impl Babelify for TsOptionalType { type Output = TSOptionalType; fn babelify(self, ctx: &Context) -> Self::Output { TSOptionalType { base: ctx.base(self.span), type_annotation: Box::alloc().init(self.type_ann.babelify(ctx)), } } } impl Babelify for TsRestType { type Output = TSRestType; fn babelify(self, ctx: &Context) -> Self::Output { TSRestType { base: ctx.base(self.span), type_annotation: Box::alloc().init(self.type_ann.babelify(ctx)), } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum TsUnionOrIntersectionTypeOutput { Union(TSUnionType), Intersection(TSIntersectionType), } impl Babelify for TsUnionOrIntersectionType { type Output = TsUnionOrIntersectionTypeOutput; fn babelify(self, ctx: &Context) -> Self::Output { match self { TsUnionOrIntersectionType::TsUnionType(u) => { TsUnionOrIntersectionTypeOutput::Union(u.babelify(ctx)) } TsUnionOrIntersectionType::TsIntersectionType(i) => { TsUnionOrIntersectionTypeOutput::Intersection(i.babelify(ctx)) } } } } impl Babelify for TsUnionType { type Output = TSUnionType; fn babelify(self, ctx: &Context) -> Self::Output { TSUnionType { base: ctx.base(self.span), types: self.types.into_iter().map(|t| t.babelify(ctx)).collect(), } } } impl Babelify for TsIntersectionType { type Output = TSIntersectionType; fn babelify(self, ctx: &Context) -> Self::Output { TSIntersectionType { base: ctx.base(self.span), types: self.types.into_iter().map(|t| t.babelify(ctx)).collect(), } } } impl Babelify for TsConditionalType { type Output = TSConditionalType; fn babelify(self, ctx: &Context) -> Self::Output { TSConditionalType { base: ctx.base(self.span), check_type: Box::alloc().init(self.check_type.babelify(ctx)), extends_type: Box::alloc().init(self.extends_type.babelify(ctx)), true_type: Box::alloc().init(self.true_type.babelify(ctx)), false_type: Box::alloc().init(self.false_type.babelify(ctx)), } } } impl Babelify for TsInferType { type Output = TSInferType; fn babelify(self, ctx: &Context) -> Self::Output { TSInferType { base: ctx.base(self.span), type_parameter: Box::alloc().init(self.type_param.babelify(ctx)), } } } impl Babelify for TsParenthesizedType { type Output = TSParenthesizedType; fn babelify(self, ctx: &Context) -> Self::Output { TSParenthesizedType { base: ctx.base(self.span), type_annotation: Box::alloc().init(self.type_ann.babelify(ctx)), } } } impl Babelify for TsTypeOperator { type Output = TSTypeOperator; fn babelify(self, ctx: &Context) -> Self::Output { TSTypeOperator { base: ctx.base(self.span), type_annotation: Box::alloc().init(self.type_ann.babelify(ctx)), operator: self.op.babelify(ctx), } } } impl Babelify for TsTypeOperatorOp { type Output = Atom; fn babelify(self, _ctx: &Context) -> Self::Output { match self { TsTypeOperatorOp::KeyOf => "keyof".into(), TsTypeOperatorOp::Unique => "unique".into(), TsTypeOperatorOp::ReadOnly => "readonly".into(), } } } impl Babelify for TsIndexedAccessType { type Output = TSIndexedAccessType; fn babelify(self, ctx: &Context) -> Self::Output { TSIndexedAccessType { base: ctx.base(self.span), object_type: Box::alloc().init(self.obj_type.babelify(ctx)), index_type: Box::alloc().init(self.index_type.babelify(ctx)), } } } // TODO(dwoznicki): I don't understand how Babel handles the +/- symbol, so this // conversion will not work properly yet. impl Babelify for TsMappedType { type Output = TSMappedType; fn babelify(self, ctx: &Context) -> Self::Output { TSMappedType { base: ctx.base(self.span), type_parameter: Box::alloc().init(self.type_param.babelify(ctx)), type_annotation: self .type_ann .map(|ann| Box::alloc().init(ann.babelify(ctx))), name_type: self.name_type.map(|t| Box::alloc().init(t.babelify(ctx))), optional: self.optional.map(|val| val == TruePlusMinus::True), readonly: self.readonly.map(|val| val == TruePlusMinus::True), } } } impl Babelify for TsLitType { type Output = TSLiteralType; fn babelify(self, ctx: &Context) -> Self::Output { TSLiteralType { base: ctx.base(self.span), literal: self.lit.babelify(ctx), } } } impl Babelify for TsLit { type Output = TSLiteralTypeLiteral; fn babelify(self, ctx: &Context) -> Self::Output { match self { TsLit::Number(n) => TSLiteralTypeLiteral::Numeric(n.babelify(ctx)), TsLit::Str(s) => TSLiteralTypeLiteral::String(s.babelify(ctx)), TsLit::Bool(b) => TSLiteralTypeLiteral::Boolean(b.babelify(ctx)), TsLit::BigInt(i) => TSLiteralTypeLiteral::BigInt(i.babelify(ctx)), _ => panic!( "illegal conversion: Cannot convert {:?} to TSLiteralTypeLiteral", &self ), } } } // TODO(dwoznicki): Babel does not appear to have a corresponding template // literal TS node. impl Babelify for TsTplLitType { type Output = String; fn babelify(self, _ctx: &Context) -> Self::Output { panic!("unimplemented"); } } impl Babelify for TsInterfaceDecl { type Output = TSInterfaceDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { TSInterfaceDeclaration { base: ctx.base(self.span), id: self.id.babelify(ctx), type_parameters: self.type_params.map(|t| t.babelify(ctx)), extends: self.extends.into_iter().next().babelify(ctx), body: self.body.babelify(ctx), declare: Some(self.declare), } } } impl Babelify for TsInterfaceBody { type Output = TSInterfaceBody; fn babelify(self, ctx: &Context) -> Self::Output { TSInterfaceBody { base: ctx.base(self.span), body: self.body.babelify(ctx), } } } impl Babelify for TsExprWithTypeArgs { type Output = TSExpressionWithTypeArguments; fn babelify(self, ctx: &Context) -> Self::Output { fn babelify_expr(expr: Expr, ctx: &Context) -> TSEntityName { match expr { Expr::Ident(id) => TSEntityName::Id(id.babelify(ctx)), Expr::Member(e) => TSEntityName::Qualified(TSQualifiedName { base: ctx.base(e.span), left: Box::new(babelify_expr(*e.obj, ctx)), right: match e.prop { MemberProp::Ident(id) => id.babelify(ctx), _ => unreachable!(), }, }), _ => unreachable!(), } } TSExpressionWithTypeArguments { base: ctx.base(self.span), expression: babelify_expr(*self.expr, ctx), type_parameters: self.type_args.map(|arg| arg.babelify(ctx)), } } } impl Babelify for TsTypeAliasDecl { type Output = TSTypeAliasDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { TSTypeAliasDeclaration { base: ctx.base(self.span), id: self.id.babelify(ctx), type_parameters: self.type_params.map(|t| t.babelify(ctx)), type_annotation: self.type_ann.babelify(ctx), declare: Some(self.declare), } } } impl Babelify for TsEnumDecl { type Output = TSEnumDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { TSEnumDeclaration { base: ctx.base(self.span), id: self.id.babelify(ctx), members: self.members.babelify(ctx), is_const: Some(self.is_const), declare: Some(self.declare), initializer: Default::default(), } } } impl Babelify for TsEnumMember { type Output = TSEnumMember; fn babelify(self, ctx: &Context) -> Self::Output { TSEnumMember { base: ctx.base(self.span), id: self.id.babelify(ctx), initializer: self.init.map(|i| Box::alloc().init(i.babelify(ctx).into())), } } } impl Babelify for TsEnumMemberId { type Output = IdOrString; fn babelify(self, ctx: &Context) -> Self::Output { match self { TsEnumMemberId::Ident(i) => IdOrString::Id(i.babelify(ctx)), TsEnumMemberId::Str(s) => IdOrString::String(s.babelify(ctx)), } } } impl Babelify for TsModuleDecl { type Output = TSModuleDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { TSModuleDeclaration { base: ctx.base(self.span), id: self.id.babelify(ctx), body: Box::alloc().init(self.body.unwrap().babelify(ctx)), declare: Some(self.declare), global: Some(self.global), } } } impl Babelify for TsNamespaceBody { type Output = TSModuleDeclBody; fn babelify(self, ctx: &Context) -> Self::Output { match self { TsNamespaceBody::TsModuleBlock(b) => TSModuleDeclBody::Block(b.babelify(ctx)), TsNamespaceBody::TsNamespaceDecl(d) => TSModuleDeclBody::Decl(d.babelify(ctx)), } } } impl Babelify for TsModuleBlock { type Output = TSModuleBlock; fn babelify(self, ctx: &Context) -> Self::Output { TSModuleBlock { base: ctx.base(self.span), body: self .body .into_iter() .map(|m| m.babelify(ctx).into()) .collect(), } } } impl Babelify for TsNamespaceDecl { type Output = TSModuleDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { TSModuleDeclaration { base: ctx.base(self.span), id: IdOrString::Id(self.id.babelify(ctx)), body: Box::alloc().init(self.body.babelify(ctx)), declare: Some(self.declare), global: Some(self.global), } } } impl Babelify for TsModuleName { type Output = IdOrString; fn babelify(self, ctx: &Context) -> Self::Output { match self { TsModuleName::Ident(i) => IdOrString::Id(i.babelify(ctx)), TsModuleName::Str(s) => IdOrString::String(s.babelify(ctx)), } } } impl Babelify for TsImportEqualsDecl { type Output = TSImportEqualsDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { TSImportEqualsDeclaration { base: ctx.base(self.span), id: self.id.babelify(ctx), module_reference: self.module_ref.babelify(ctx), is_export: self.is_export, } } } impl Babelify for TsModuleRef { type Output = TSImportEqualsDeclModuleRef; fn babelify(self, ctx: &Context) -> Self::Output { match self { TsModuleRef::TsEntityName(n) => TSImportEqualsDeclModuleRef::Name(n.babelify(ctx)), TsModuleRef::TsExternalModuleRef(e) => { TSImportEqualsDeclModuleRef::External(e.babelify(ctx)) } } } } impl Babelify for TsExternalModuleRef { type Output = TSExternalModuleReference; fn babelify(self, ctx: &Context) -> Self::Output { TSExternalModuleReference { base: ctx.base(self.span), expression: self.expr.babelify(ctx), } } } impl Babelify for TsExportAssignment { type Output = TSExportAssignment; fn babelify(self, ctx: &Context) -> Self::Output { TSExportAssignment { base: ctx.base(self.span), expression: Box::alloc().init(self.expr.babelify(ctx).into()), } } } impl Babelify for TsNamespaceExportDecl { type Output = TSNamespaceExportDeclaration; fn babelify(self, ctx: &Context) -> Self::Output { TSNamespaceExportDeclaration { base: ctx.base(self.span), id: self.id.babelify(ctx), } } } impl Babelify for TsAsExpr { type Output = TSAsExpression; fn babelify(self, ctx: &Context) -> Self::Output { TSAsExpression { base: ctx.base(self.span), expression: Box::alloc().init(self.expr.babelify(ctx).into()), type_annotation: self.type_ann.babelify(ctx), } } } impl Babelify for TsTypeAssertion { type Output = TSTypeAssertion; fn babelify(self, ctx: &Context) -> Self::Output { TSTypeAssertion { base: ctx.base(self.span), expression: Box::alloc().init(self.expr.babelify(ctx).into()), type_annotation: self.type_ann.babelify(ctx), } } } impl Babelify for TsNonNullExpr { type Output = TSNonNullExpression; fn babelify(self, ctx: &Context) -> Self::Output { TSNonNullExpression { base: ctx.base(self.span), expression: Box::alloc().init(self.expr.babelify(ctx).into()), } } } impl Babelify for Accessibility { type Output = Access; fn babelify(self, _ctx: &Context) -> Self::Output { match self { Accessibility::Public => Access::Public, Accessibility::Protected => Access::Protected, Accessibility::Private => Access::Private, } } } // TODO(dwoznicki): There does not appear to be a corresponding Babel node for // this. impl Babelify for TsConstAssertion { type Output = String; fn babelify(self, _ctx: &Context) -> Self::Output { panic!("unimplemented"); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/lib.rs
Rust
#![deny(clippy::all)] #![allow(clippy::large_enum_variant)] #![allow(clippy::upper_case_acronyms)] use std::convert::Infallible; pub mod babelify; pub mod swcify; pub type Never = Infallible;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/swcify/class.rs
Rust
use swc_ecma_ast::{ ClassMember, Expr, Function, MemberExpr, MemberProp, MethodKind, ParamOrTsParamProp, TsExprWithTypeArgs, }; use swc_estree_ast::{ ClassBody, ClassBodyEl, ClassImpl, ClassMethodKind, TSEntityName, TSExpressionWithTypeArguments, TSQualifiedName, }; use super::Context; use crate::swcify::Swcify; impl Swcify for ClassBody { type Output = Vec<ClassMember>; fn swcify(self, ctx: &Context) -> Self::Output { self.body.swcify(ctx) } } impl Swcify for ClassBodyEl { type Output = ClassMember; fn swcify(self, ctx: &Context) -> Self::Output { match self { ClassBodyEl::Method(v) => v.swcify(ctx), ClassBodyEl::PrivateMethod(v) => v.swcify(ctx).into(), ClassBodyEl::Prop(v) => v.swcify(ctx).into(), ClassBodyEl::PrivateProp(v) => v.swcify(ctx).into(), _ => { unimplemented!("swcify: {:?}", self) } } } } impl Swcify for swc_estree_ast::ClassMethod { type Output = swc_ecma_ast::ClassMember; fn swcify(self, ctx: &Context) -> Self::Output { match self.kind.unwrap_or(ClassMethodKind::Method) { ClassMethodKind::Get | ClassMethodKind::Set | ClassMethodKind::Method => { swc_ecma_ast::ClassMethod { span: ctx.span(&self.base), key: self.key.swcify(ctx), function: Function { params: self.params.swcify(ctx), decorators: self.decorators.swcify(ctx).unwrap_or_default(), span: ctx.span(&self.base), body: Some(self.body.swcify(ctx)), is_generator: self.generator.unwrap_or_default(), is_async: self.is_async.unwrap_or_default(), type_params: self.type_parameters.swcify(ctx).flatten().map(Box::new), return_type: self.return_type.swcify(ctx).flatten().map(Box::new), ..Default::default() } .into(), kind: self .kind .map(|kind| match kind { ClassMethodKind::Get => MethodKind::Getter, ClassMethodKind::Set => MethodKind::Setter, ClassMethodKind::Method => MethodKind::Getter, ClassMethodKind::Constructor => { unreachable!() } }) .unwrap_or(MethodKind::Method), is_static: self.is_static.unwrap_or_default(), accessibility: self.accessibility.swcify(ctx), is_abstract: self.is_abstract.unwrap_or_default(), is_optional: self.optional.unwrap_or_default(), is_override: false, } .into() } ClassMethodKind::Constructor => swc_ecma_ast::Constructor { span: ctx.span(&self.base), key: self.key.swcify(ctx), params: self .params .into_iter() .map(|v| v.swcify(ctx)) .map(ParamOrTsParamProp::Param) .collect(), body: Some(self.body.swcify(ctx)), accessibility: self.accessibility.swcify(ctx), is_optional: self.optional.unwrap_or_default(), ..Default::default() } .into(), } } } impl Swcify for swc_estree_ast::ClassPrivateMethod { type Output = swc_ecma_ast::PrivateMethod; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::PrivateMethod { span: ctx.span(&self.base), key: self.key.swcify(ctx), function: Function { params: self.params.swcify(ctx), decorators: self.decorators.swcify(ctx).unwrap_or_default(), span: ctx.span(&self.base), body: Some(self.body.swcify(ctx)), is_generator: self.generator.unwrap_or_default(), is_async: self.is_async.unwrap_or_default(), type_params: self.type_parameters.swcify(ctx).flatten().map(Box::new), return_type: self.return_type.swcify(ctx).flatten().map(Box::new), ..Default::default() } .into(), kind: match self.kind.unwrap_or(ClassMethodKind::Method) { ClassMethodKind::Get => MethodKind::Getter, ClassMethodKind::Set => MethodKind::Setter, ClassMethodKind::Method => MethodKind::Getter, ClassMethodKind::Constructor => { unreachable!() } }, is_static: self.is_static.unwrap_or_default(), accessibility: self.accessibility.swcify(ctx), is_abstract: self.is_abstract.unwrap_or_default(), is_optional: self.optional.unwrap_or_default(), is_override: false, } } } impl Swcify for swc_estree_ast::ClassProperty { type Output = swc_ecma_ast::ClassProp; fn swcify(self, ctx: &Context) -> Self::Output { let key = self.key.swcify(ctx); swc_ecma_ast::ClassProp { span: ctx.span(&self.base), key, value: self.value.swcify(ctx), type_ann: self.type_annotation.swcify(ctx).flatten().map(Box::new), is_static: self.is_static.unwrap_or(false), decorators: self.decorators.swcify(ctx).unwrap_or_default(), accessibility: self.accessibility.swcify(ctx), is_abstract: self.is_abstract.unwrap_or_default(), is_optional: self.optional.unwrap_or_default(), is_override: false, readonly: self.readonly.unwrap_or_default(), declare: self.declare.unwrap_or_default(), definite: self.definite.unwrap_or_default(), } } } impl Swcify for swc_estree_ast::ClassPrivateProperty { type Output = swc_ecma_ast::PrivateProp; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::PrivateProp { span: ctx.span(&self.base), key: self.key.swcify(ctx), value: self.value.swcify(ctx), type_ann: self.type_annotation.swcify(ctx).flatten().map(Box::new), is_static: false, decorators: Default::default(), accessibility: Default::default(), is_optional: false, is_override: false, readonly: false, definite: false, ctxt: Default::default(), } } } impl Swcify for ClassImpl { type Output = TsExprWithTypeArgs; fn swcify(self, ctx: &Context) -> Self::Output { match self { ClassImpl::TSExpr(v) => v.swcify(ctx), ClassImpl::Implements(_) => { unreachable!() } } } } impl Swcify for TSExpressionWithTypeArguments { type Output = TsExprWithTypeArgs; fn swcify(self, ctx: &Context) -> Self::Output { // The reason why we have special logic for converting `TSEntityName` here, // instead of updating or using logic of `TSEntityName`, // is that `TSEntityName` can be used somewhere, // if we change its conversion logic, it will break. fn swcify_expr(expr: TSEntityName, ctx: &Context) -> Box<Expr> { match expr { TSEntityName::Id(v) => v.swcify(ctx).into(), TSEntityName::Qualified(v) => swcify_qualified_name(v, ctx), } } fn swcify_qualified_name(qualified_name: TSQualifiedName, ctx: &Context) -> Box<Expr> { MemberExpr { obj: swcify_expr(*qualified_name.left, ctx), prop: MemberProp::Ident(qualified_name.right.swcify(ctx).into()), span: ctx.span(&qualified_name.base), } .into() } TsExprWithTypeArgs { span: ctx.span(&self.base), expr: swcify_expr(self.expression, ctx), type_args: self.type_parameters.swcify(ctx).map(Box::new), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/swcify/ctx.rs
Rust
use swc_common::{sync::Lrc, BytePos, FileName, SourceFile, SourceMap, Span, DUMMY_SP}; use swc_estree_ast::{BaseNode, LineCol, Loc}; use swc_node_comments::SwcComments; pub struct Context { #[allow(unused)] pub(crate) cm: Lrc<SourceMap>, pub(crate) fm: Lrc<SourceFile>, #[allow(unused)] pub(crate) comments: SwcComments, } impl Context { fn locate_line_col(&self, loc: LineCol) -> BytePos { if let Some(&line_start) = self.fm.analyze().lines.get(loc.line) { line_start + BytePos(loc.column as _) } else { BytePos(0) } } fn locate_loc(&self, loc: Option<Loc>) -> Span { let loc = match loc { Some(v) => v, None => return DUMMY_SP, }; let start = self.locate_line_col(loc.start); let end = self.locate_line_col(loc.end); Span::new(start, end) } pub(crate) fn span(&self, node: &BaseNode) -> Span { let span = self.locate_loc(node.loc); if !span.is_dummy() { return span; } let start = node .start .map(|offset| self.fm.start_pos + BytePos(offset as _)) .unwrap_or(BytePos::DUMMY); let end = node .end .map(|offset| self.fm.start_pos + BytePos(offset as _)) .unwrap_or(BytePos::DUMMY); Span::new(start, end) } /// This accepts source string because the spans of an ast node of swc are /// stored as interned. /// /// This method allocate a new [SourceFile] in the given `cm`. pub fn new(cm: Lrc<SourceMap>, comments: SwcComments, filename: FileName, src: String) -> Self { let fm = cm.new_source_file(filename.into(), src); Self::new_without_alloc(cm, comments, fm) } pub fn new_without_alloc( cm: Lrc<SourceMap>, comments: SwcComments, fm: Lrc<SourceFile>, ) -> Self { Self { cm, comments, fm } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/swcify/expr.rs
Rust
use swc_common::Spanned; use swc_ecma_ast::{ op, ArrayLit, ArrowExpr, AssignExpr, AwaitExpr, BinExpr, BinaryOp, BindingIdent, BlockStmtOrExpr, CallExpr, Callee, ClassExpr, ComputedPropName, CondExpr, Expr, ExprOrSpread, FnExpr, Function, Ident, Import, JSXAttr, JSXAttrOrSpread, JSXAttrValue, JSXEmptyExpr, JSXExpr, JSXExprContainer, JSXMemberExpr, JSXObject, KeyValueProp, Lit, MemberExpr, MemberProp, MetaPropExpr, MetaPropKind, MethodProp, NewExpr, ObjectLit, OptCall, OptChainBase, OptChainExpr, ParenExpr, Prop, PropName, PropOrSpread, SeqExpr, SpreadElement, SuperProp, SuperPropExpr, TaggedTpl, ThisExpr, TsAsExpr, TsNonNullExpr, TsTypeAssertion, TsTypeParamInstantiation, UnaryExpr, UnaryOp, UpdateExpr, YieldExpr, }; use swc_estree_ast::{ Arg, ArrayExprEl, ArrayExpression, ArrowFuncExprBody, ArrowFunctionExpression, AssignmentExpression, AwaitExpression, BinaryExprLeft, BinaryExprOp, BinaryExpression, BindExpression, CallExpression, Callee as BabelCallee, ClassExpression, ConditionalExpression, DoExpression, Expression, FunctionExpression, Identifier, Import as BabelImport, JSXAttrVal, JSXAttribute, JSXEmptyExpression, JSXExprContainerExpr, JSXExpressionContainer, JSXMemberExprObject, JSXMemberExpression, JSXSpreadAttribute, Literal, LogicalExprOp, LogicalExpression, MemberExprProp, MemberExpression, MetaProperty, ModuleExpression, NewExpression, ObjectExprProp, ObjectExpression, ObjectKey, ObjectMethod, ObjectPropVal, ObjectProperty, OptionalCallExpression, OptionalMemberExprProp, OptionalMemberExpression, ParenthesizedExpression, PatternLike, PipelinePrimaryTopicReference, RecordExpression, SequenceExpression, TSAsExpression, TSNonNullExpression, TSTypeAssertion, TaggedTemplateExprTypeParams, TaggedTemplateExpression, ThisExpression, TupleExpression, TypeCastExpression, UnaryExprOp, UnaryExpression, UpdateExprOp, UpdateExpression, YieldExpression, }; use super::Context; use crate::{swcify::Swcify, Never}; impl Swcify for Expression { type Output = Box<Expr>; fn swcify(self, ctx: &Context) -> Self::Output { Box::new(match self { Expression::Array(e) => e.swcify(ctx).into(), Expression::Assignment(e) => e.swcify(ctx).into(), Expression::Binary(e) => e.swcify(ctx).into(), Expression::Call(e) => e.swcify(ctx).into(), Expression::Conditional(e) => e.swcify(ctx).into(), Expression::Func(e) => e.swcify(ctx).into(), Expression::Id(e) => e.swcify(ctx).id.into(), Expression::Literal(Literal::String(e)) => e.swcify(ctx).into(), Expression::Literal(Literal::Numeric(e)) => e.swcify(ctx).into(), Expression::Literal(Literal::Null(e)) => Lit::from(e.swcify(ctx)).into(), Expression::Literal(Literal::Boolean(e)) => Lit::from(e.swcify(ctx)).into(), Expression::Literal(Literal::RegExp(e)) => Lit::from(e.swcify(ctx)).into(), Expression::Logical(e) => e.swcify(ctx).into(), Expression::Member(e) => e.swcify(ctx), Expression::New(e) => e.swcify(ctx).into(), Expression::Object(e) => e.swcify(ctx).into(), Expression::Sequence(e) => e.swcify(ctx).into(), Expression::Parenthesized(e) => e.swcify(ctx).into(), Expression::This(e) => e.swcify(ctx).into(), Expression::Unary(e) => e.swcify(ctx).into(), Expression::Update(e) => e.swcify(ctx).into(), Expression::ArrowFunc(e) => e.swcify(ctx).into(), Expression::Class(e) => e.swcify(ctx).into(), Expression::MetaProp(e) => e.swcify(ctx).into(), Expression::Super(..) => unreachable!(), Expression::TaggedTemplate(e) => e.swcify(ctx).into(), Expression::TemplateLiteral(e) => e.swcify(ctx).into(), Expression::Yield(e) => e.swcify(ctx).into(), Expression::Await(e) => e.swcify(ctx).into(), Expression::Literal(Literal::BigInt(e)) => e.swcify(ctx).into(), Expression::OptionalMember(e) => e.swcify(ctx).into(), Expression::OptionalCall(e) => e.swcify(ctx).into(), Expression::JSXElement(e) => return e.swcify(ctx).into(), Expression::JSXFragment(e) => e.swcify(ctx).into(), Expression::Literal(Literal::Decimal(e)) => e.swcify(ctx).into(), Expression::TSAs(e) => e.swcify(ctx).into(), Expression::TSTypeAssertion(e) => e.swcify(ctx).into(), Expression::TSNonNull(e) => e.swcify(ctx).into(), _ => { unimplemented!("swcify: {:?}", self) } }) } } impl Swcify for ArrayExpression { type Output = ArrayLit; fn swcify(self, ctx: &Context) -> Self::Output { ArrayLit { span: ctx.span(&self.base), elems: self.elements.swcify(ctx), } } } impl Swcify for AssignmentExpression { type Output = AssignExpr; fn swcify(self, ctx: &Context) -> Self::Output { AssignExpr { span: ctx.span(&self.base), op: self.operator.parse().unwrap_or_else(|_| { panic!( "failed to convert `AssignmentExpression` of babel: Unknown assignment \ operator {}", self.operator, ) }), left: self.left.swcify(ctx).try_into().unwrap(), right: self.right.swcify(ctx), } } } impl Swcify for BinaryExpression { type Output = BinExpr; fn swcify(self, ctx: &Context) -> Self::Output { BinExpr { span: ctx.span(&self.base), op: self.operator.swcify(ctx), left: self.left.swcify(ctx), right: self.right.swcify(ctx), } } } impl Swcify for swc_estree_ast::PrivateName { type Output = swc_ecma_ast::PrivateName; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::PrivateName { span: ctx.span(&self.base), name: self.id.swcify(ctx).sym.clone(), } } } impl Swcify for BinaryExprLeft { type Output = Box<Expr>; fn swcify(self, ctx: &Context) -> Self::Output { match self { BinaryExprLeft::Private(e) => e.swcify(ctx).into(), BinaryExprLeft::Expr(e) => e.swcify(ctx), } } } impl Swcify for BinaryExprOp { type Output = BinaryOp; fn swcify(self, _: &Context) -> Self::Output { match self { BinaryExprOp::Addition => { op!(bin, "+") } BinaryExprOp::Subtraction => { op!(bin, "-") } BinaryExprOp::Division => { op!("/") } BinaryExprOp::Remainder => { op!("%") } BinaryExprOp::Multiplication => { op!("*") } BinaryExprOp::Exponentiation => { op!("**") } BinaryExprOp::And => { op!("&") } BinaryExprOp::Or => { op!("|") } BinaryExprOp::RightShift => { op!(">>") } BinaryExprOp::UnsignedRightShift => { op!(">>>") } BinaryExprOp::LeftShift => { op!("<<") } BinaryExprOp::Xor => { op!("^") } BinaryExprOp::Equal => { op!("==") } BinaryExprOp::StrictEqual => { op!("===") } BinaryExprOp::NotEqual => { op!("!=") } BinaryExprOp::StrictNotEqual => { op!("!==") } BinaryExprOp::In => { op!("in") } BinaryExprOp::Instanceof => { op!("instanceof") } BinaryExprOp::GreaterThan => { op!(">") } BinaryExprOp::LessThan => { op!("<") } BinaryExprOp::GreaterThanOrEqual => { op!(">=") } BinaryExprOp::LessThanOrEqual => { op!("<=") } } } } impl Swcify for BabelCallee { type Output = Callee; fn swcify(self, ctx: &Context) -> Self::Output { match self { BabelCallee::V8Id(_) => { unreachable!("what is v8 id?") } BabelCallee::Expr(e) => match *e { Expression::Super(s) => Callee::Super(s.swcify(ctx)), Expression::Import(s) => Callee::Import(s.swcify(ctx)), _ => Callee::Expr(e.swcify(ctx)), }, } } } impl Swcify for CallExpression { type Output = CallExpr; fn swcify(self, ctx: &Context) -> Self::Output { CallExpr { span: ctx.span(&self.base), callee: self.callee.swcify(ctx), args: self .arguments .swcify(ctx) .into_iter() .map(|v| v.expect("failed to swcify arguments")) .collect(), type_args: self.type_parameters.swcify(ctx).map(Box::new), ..Default::default() } } } impl Swcify for Arg { type Output = Option<ExprOrSpread>; fn swcify(self, ctx: &Context) -> Self::Output { Some(match self { Arg::Spread(s) => ExprOrSpread { spread: Some(ctx.span(&s.base)), expr: s.argument.swcify(ctx), }, Arg::JSXName(e) => ExprOrSpread { spread: None, expr: e.swcify(ctx).into(), }, Arg::Placeholder(_) => return None, Arg::Expr(e) => ExprOrSpread { spread: None, expr: e.swcify(ctx), }, }) } } impl Swcify for ConditionalExpression { type Output = CondExpr; fn swcify(self, ctx: &Context) -> Self::Output { CondExpr { span: ctx.span(&self.base), test: self.test.swcify(ctx), cons: self.consequent.swcify(ctx), alt: self.alternate.swcify(ctx), } } } impl Swcify for FunctionExpression { type Output = FnExpr; fn swcify(self, ctx: &Context) -> Self::Output { FnExpr { ident: self.id.swcify(ctx).map(|v| v.into()), function: Box::new(Function { params: self.params.swcify(ctx), decorators: Default::default(), span: ctx.span(&self.base), body: Some(self.body.swcify(ctx)), is_generator: self.generator.unwrap_or(false), is_async: self.is_async.unwrap_or(false), type_params: self.type_parameters.swcify(ctx).flatten().map(Box::new), return_type: self.return_type.swcify(ctx).flatten().map(Box::new), ..Default::default() }), } } } impl Swcify for Identifier { type Output = BindingIdent; fn swcify(self, ctx: &Context) -> Self::Output { BindingIdent { id: Ident { span: ctx.span(&self.base), sym: self.name, optional: self.optional.unwrap_or(false), ctxt: Default::default(), }, type_ann: self.type_annotation.swcify(ctx).flatten().map(Box::new), } } } impl Swcify for LogicalExprOp { type Output = BinaryOp; fn swcify(self, _: &Context) -> Self::Output { match self { LogicalExprOp::Or => { op!("||") } LogicalExprOp::And => { op!("&&") } LogicalExprOp::Nullish => { op!("??") } } } } impl Swcify for LogicalExpression { type Output = BinExpr; fn swcify(self, ctx: &Context) -> Self::Output { BinExpr { span: ctx.span(&self.base), op: self.operator.swcify(ctx), left: self.left.swcify(ctx), right: self.right.swcify(ctx), } } } impl Swcify for MemberExpression { type Output = Expr; fn swcify(self, ctx: &Context) -> Self::Output { match *self.object { Expression::Super(s) => SuperPropExpr { span: ctx.span(&self.base), obj: s.swcify(ctx), prop: match (*self.property, self.computed) { (MemberExprProp::Id(i), false) => SuperProp::Ident(i.swcify(ctx).into()), (MemberExprProp::Expr(e), true) => { let expr = e.swcify(ctx); SuperProp::Computed(ComputedPropName { span: expr.span(), expr, }) } _ => unreachable!(), }, } .into(), _ => MemberExpr { span: ctx.span(&self.base), obj: self.object.swcify(ctx), prop: match (*self.property, self.computed) { (MemberExprProp::Id(i), false) => MemberProp::Ident(i.swcify(ctx).into()), (MemberExprProp::PrivateName(e), false) => { MemberProp::PrivateName(e.swcify(ctx)) } (MemberExprProp::Expr(e), true) => { let expr = e.swcify(ctx); MemberProp::Computed(ComputedPropName { span: expr.span(), expr, }) } _ => unreachable!(), }, } .into(), } } } impl Swcify for NewExpression { type Output = NewExpr; fn swcify(self, ctx: &Context) -> Self::Output { NewExpr { span: ctx.span(&self.base), callee: match self.callee { BabelCallee::V8Id(..) => { unreachable!() } BabelCallee::Expr(e) => e.swcify(ctx), }, args: Some( self.arguments .swcify(ctx) .into_iter() .map(|v| v.expect("failed to swcify arguments")) .collect(), ), type_args: self.type_parameters.swcify(ctx).map(From::from), ..Default::default() } } } impl Swcify for ObjectExpression { type Output = ObjectLit; fn swcify(self, ctx: &Context) -> Self::Output { ObjectLit { span: ctx.span(&self.base), props: self.properties.swcify(ctx), } } } impl Swcify for ObjectExprProp { type Output = PropOrSpread; fn swcify(self, ctx: &Context) -> Self::Output { match self { ObjectExprProp::Method(m) => PropOrSpread::Prop(Box::new(Prop::Method(m.swcify(ctx)))), ObjectExprProp::Prop(p) => PropOrSpread::Prop(Box::new(Prop::KeyValue(p.swcify(ctx)))), ObjectExprProp::Spread(p) => PropOrSpread::Spread(SpreadElement { // TODO: Use exact span dot3_token: ctx.span(&p.base), expr: p.argument.swcify(ctx), }), } } } impl Swcify for ObjectMethod { type Output = MethodProp; fn swcify(self, ctx: &Context) -> Self::Output { MethodProp { key: self.key.swcify(ctx), function: Box::new(Function { params: self.params.swcify(ctx), decorators: self.decorator.swcify(ctx).unwrap_or_default(), span: ctx.span(&self.base), body: Some(self.body.swcify(ctx)), is_generator: self.generator.unwrap_or(false), is_async: self.is_async.unwrap_or(false), type_params: self.type_parameters.swcify(ctx).flatten().map(Box::new), return_type: self.return_type.swcify(ctx).flatten().map(Box::new), ..Default::default() }), } } } impl Swcify for swc_estree_ast::Decorator { type Output = swc_ecma_ast::Decorator; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::Decorator { span: ctx.span(&self.base), expr: self.expression.swcify(ctx), } } } impl Swcify for ObjectKey { type Output = PropName; fn swcify(self, ctx: &Context) -> Self::Output { match self { ObjectKey::Id(v) => PropName::Ident(v.swcify(ctx).into()), ObjectKey::String(v) => PropName::Str(v.swcify(ctx)), ObjectKey::Numeric(v) => PropName::Num(v.swcify(ctx)), ObjectKey::Expr(v) => { let expr = v.swcify(ctx); PropName::Computed(ComputedPropName { span: expr.span(), expr, }) } } } } impl Swcify for ObjectProperty { type Output = KeyValueProp; fn swcify(self, ctx: &Context) -> Self::Output { KeyValueProp { key: self.key.swcify(ctx), value: match self.value { ObjectPropVal::Pattern(pat) => match pat { PatternLike::Id(i) => i.swcify(ctx).into(), _ => { panic!("swc does not support ObjectPropVal::Pattern({:?})", pat) } }, ObjectPropVal::Expr(e) => e.swcify(ctx), }, } } } impl Swcify for SequenceExpression { type Output = SeqExpr; fn swcify(self, ctx: &Context) -> Self::Output { SeqExpr { span: ctx.span(&self.base), exprs: self.expressions.swcify(ctx), } } } impl Swcify for ParenthesizedExpression { type Output = ParenExpr; fn swcify(self, ctx: &Context) -> Self::Output { ParenExpr { span: ctx.span(&self.base), expr: self.expression.swcify(ctx), } } } impl Swcify for ThisExpression { type Output = ThisExpr; fn swcify(self, ctx: &Context) -> Self::Output { ThisExpr { span: ctx.span(&self.base), } } } impl Swcify for UnaryExpression { type Output = UnaryExpr; fn swcify(self, ctx: &Context) -> Self::Output { UnaryExpr { span: ctx.span(&self.base), op: self.operator.swcify(ctx), arg: self.argument.swcify(ctx), } } } impl Swcify for UnaryExprOp { type Output = UnaryOp; fn swcify(self, _: &Context) -> Self::Output { match self { UnaryExprOp::Void => { op!("void") } UnaryExprOp::Throw => { panic!("swc does not support throw expressions") } UnaryExprOp::Delete => { op!("delete") } UnaryExprOp::LogicalNot => { op!("!") } UnaryExprOp::Plus => { op!(unary, "+") } UnaryExprOp::Negation => { op!(unary, "-") } UnaryExprOp::BitwiseNot => { op!("~") } UnaryExprOp::Typeof => { op!("typeof") } } } } impl Swcify for UpdateExpression { type Output = UpdateExpr; fn swcify(self, ctx: &Context) -> Self::Output { UpdateExpr { span: ctx.span(&self.base), op: match self.operator { UpdateExprOp::Increment => { op!("++") } UpdateExprOp::Decrement => { op!("--") } }, prefix: self.prefix, arg: self.argument.swcify(ctx), } } } impl Swcify for ArrowFunctionExpression { type Output = ArrowExpr; fn swcify(self, ctx: &Context) -> Self::Output { ArrowExpr { span: ctx.span(&self.base), params: self.params.into_iter().map(|v| v.swcify(ctx).pat).collect(), body: Box::new(self.body.swcify(ctx)), is_async: self.is_async, is_generator: self.generator, type_params: self.type_parameters.swcify(ctx).flatten().map(Box::new), return_type: self.return_type.swcify(ctx).flatten().map(Box::new), ..Default::default() } } } impl Swcify for ArrowFuncExprBody { type Output = BlockStmtOrExpr; fn swcify(self, ctx: &Context) -> Self::Output { match self { ArrowFuncExprBody::Block(v) => BlockStmtOrExpr::BlockStmt(v.swcify(ctx)), ArrowFuncExprBody::Expr(v) => BlockStmtOrExpr::Expr(v.swcify(ctx)), } } } impl Swcify for ClassExpression { type Output = ClassExpr; fn swcify(self, ctx: &Context) -> Self::Output { ClassExpr { ident: self.id.swcify(ctx).map(|v| v.into()), class: Box::new(swc_ecma_ast::Class { span: ctx.span(&self.base), decorators: self.decorators.swcify(ctx).unwrap_or_default(), body: self.body.swcify(ctx), super_class: self.super_class.swcify(ctx), is_abstract: false, type_params: self.type_parameters.swcify(ctx).flatten().map(Box::new), super_type_params: self.super_type_parameters.swcify(ctx).map(Box::new), implements: self.implements.swcify(ctx).unwrap_or_default(), ..Default::default() }), } } } impl Swcify for MetaProperty { type Output = MetaPropExpr; fn swcify(self, ctx: &Context) -> Self::Output { let meta: Ident = self.meta.swcify(ctx).into(); let prop: Ident = self.property.swcify(ctx).into(); match (&*meta.sym, &*prop.sym) { ("new", "target") => MetaPropExpr { kind: MetaPropKind::NewTarget, span: ctx.span(&self.base), }, ("import", "meta") => MetaPropExpr { kind: MetaPropKind::NewTarget, span: ctx.span(&self.base), }, _ => unreachable!("there are only two kind of meta prop"), } } } impl Swcify for swc_estree_ast::Super { type Output = swc_ecma_ast::Super; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::Super { span: ctx.span(&self.base), } } } impl Swcify for TaggedTemplateExpression { type Output = TaggedTpl; fn swcify(self, ctx: &Context) -> Self::Output { TaggedTpl { span: ctx.span(&self.base), tag: self.tag.swcify(ctx), type_params: self.type_parameters.swcify(ctx).map(From::from), tpl: Box::new(self.quasi.swcify(ctx)), ..Default::default() } } } impl Swcify for TaggedTemplateExprTypeParams { type Output = TsTypeParamInstantiation; fn swcify(self, ctx: &Context) -> Self::Output { match self { TaggedTemplateExprTypeParams::Flow(_) => unimplemented!("flow types"), TaggedTemplateExprTypeParams::TS(v) => v.swcify(ctx), } } } impl Swcify for YieldExpression { type Output = YieldExpr; fn swcify(self, ctx: &Context) -> Self::Output { YieldExpr { span: ctx.span(&self.base), arg: self.argument.swcify(ctx), delegate: self.delegate, } } } impl Swcify for AwaitExpression { type Output = AwaitExpr; fn swcify(self, ctx: &Context) -> Self::Output { AwaitExpr { span: ctx.span(&self.base), arg: self.argument.swcify(ctx), } } } impl Swcify for BabelImport { type Output = Import; fn swcify(self, ctx: &Context) -> Self::Output { Import { span: ctx.span(&self.base), // TODO phase: Default::default(), } } } impl Swcify for OptionalMemberExpression { type Output = OptChainExpr; fn swcify(self, ctx: &Context) -> Self::Output { OptChainExpr { span: ctx.span(&self.base), // TODO: Use correct span. optional: self.optional, base: Box::new(OptChainBase::Member(MemberExpr { span: ctx.span(&self.base), obj: self.object.swcify(ctx), prop: match (self.property, self.computed) { (OptionalMemberExprProp::Id(i), false) => { MemberProp::Ident(i.swcify(ctx).into()) } (OptionalMemberExprProp::Expr(e), true) => { let expr = e.swcify(ctx); MemberProp::Computed(ComputedPropName { span: expr.span(), expr, }) } _ => unreachable!(), }, })), } } } impl Swcify for OptionalMemberExprProp { type Output = Box<Expr>; fn swcify(self, ctx: &Context) -> Self::Output { match self { OptionalMemberExprProp::Id(v) => v.swcify(ctx).into(), OptionalMemberExprProp::Expr(v) => v.swcify(ctx), } } } impl Swcify for OptionalCallExpression { type Output = OptChainExpr; fn swcify(self, ctx: &Context) -> Self::Output { OptChainExpr { span: ctx.span(&self.base), optional: self.optional, base: Box::new(OptChainBase::Call(OptCall { span: ctx.span(&self.base), callee: self.callee.swcify(ctx), args: self.arguments.swcify(ctx).into_iter().flatten().collect(), type_args: self.type_parameters.swcify(ctx).map(From::from), ..Default::default() })), } } } impl Swcify for TypeCastExpression { type Output = Never; fn swcify(self, _: &Context) -> Self::Output { unimplemented!("flow type cast") } } impl Swcify for swc_estree_ast::JSXElement { type Output = swc_ecma_ast::JSXElement; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::JSXElement { span: ctx.span(&self.base), opening: self.opening_element.swcify(ctx), children: self.children.swcify(ctx), closing: self.closing_element.swcify(ctx), } } } impl Swcify for swc_estree_ast::JSXOpeningElement { type Output = swc_ecma_ast::JSXOpeningElement; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::JSXOpeningElement { span: ctx.span(&self.base), name: self.name.swcify(ctx), attrs: self.attributes.swcify(ctx), self_closing: self.self_closing, type_args: None, } } } impl Swcify for swc_estree_ast::JSXElementName { type Output = swc_ecma_ast::JSXElementName; fn swcify(self, ctx: &Context) -> Self::Output { match self { swc_estree_ast::JSXElementName::Id(v) => { swc_ecma_ast::JSXElementName::Ident(v.swcify(ctx)) } swc_estree_ast::JSXElementName::Expr(v) => { swc_ecma_ast::JSXElementName::JSXMemberExpr(v.swcify(ctx)) } swc_estree_ast::JSXElementName::Name(v) => { swc_ecma_ast::JSXElementName::JSXNamespacedName(v.swcify(ctx)) } } } } impl Swcify for JSXMemberExpression { type Output = JSXMemberExpr; fn swcify(self, ctx: &Context) -> Self::Output { JSXMemberExpr { span: ctx.span(&self.base), obj: self.object.swcify(ctx), prop: self.property.swcify(ctx).into(), } } } impl Swcify for JSXMemberExprObject { type Output = JSXObject; fn swcify(self, ctx: &Context) -> Self::Output { match self { JSXMemberExprObject::Expr(e) => JSXObject::JSXMemberExpr(Box::new(e.swcify(ctx))), JSXMemberExprObject::Id(e) => JSXObject::Ident(e.swcify(ctx)), } } } impl Swcify for swc_estree_ast::JSXOpeningElAttr { type Output = JSXAttrOrSpread; fn swcify(self, ctx: &Context) -> Self::Output { match self { swc_estree_ast::JSXOpeningElAttr::Attr(v) => JSXAttrOrSpread::JSXAttr(v.swcify(ctx)), swc_estree_ast::JSXOpeningElAttr::Spread(v) => { JSXAttrOrSpread::SpreadElement(v.swcify(ctx)) } } } } impl Swcify for JSXAttribute { type Output = JSXAttr; fn swcify(self, ctx: &Context) -> Self::Output { JSXAttr { span: ctx.span(&self.base), name: self.name.swcify(ctx), value: self.value.swcify(ctx), } } } impl Swcify for swc_estree_ast::JSXAttrName { type Output = swc_ecma_ast::JSXAttrName; fn swcify(self, ctx: &Context) -> Self::Output { match self { swc_estree_ast::JSXAttrName::Id(v) => { swc_ecma_ast::JSXAttrName::Ident(v.swcify(ctx).into()) } swc_estree_ast::JSXAttrName::Name(v) => { swc_ecma_ast::JSXAttrName::JSXNamespacedName(v.swcify(ctx)) } } } } impl Swcify for JSXAttrVal { type Output = JSXAttrValue; fn swcify(self, ctx: &Context) -> Self::Output { match self { JSXAttrVal::Element(v) => JSXAttrValue::JSXElement(Box::new(v.swcify(ctx))), JSXAttrVal::Fragment(v) => JSXAttrValue::JSXFragment(v.swcify(ctx)), JSXAttrVal::String(v) => JSXAttrValue::Lit(Lit::Str(v.swcify(ctx))), JSXAttrVal::Expr(v) => JSXAttrValue::JSXExprContainer(v.swcify(ctx)), } } } impl Swcify for JSXExpressionContainer { type Output = JSXExprContainer; fn swcify(self, ctx: &Context) -> Self::Output { JSXExprContainer { span: ctx.span(&self.base), expr: self.expression.swcify(ctx), } } } impl Swcify for JSXExprContainerExpr { type Output = JSXExpr; fn swcify(self, ctx: &Context) -> Self::Output { match self { JSXExprContainerExpr::Empty(v) => JSXExpr::JSXEmptyExpr(v.swcify(ctx)), JSXExprContainerExpr::Expr(v) => JSXExpr::Expr(v.swcify(ctx)), } } } impl Swcify for JSXEmptyExpression { type Output = JSXEmptyExpr; fn swcify(self, ctx: &Context) -> Self::Output { JSXEmptyExpr { span: ctx.span(&self.base), } } } impl Swcify for JSXSpreadAttribute { type Output = SpreadElement; fn swcify(self, ctx: &Context) -> Self::Output { SpreadElement { dot3_token: ctx.span(&self.base), expr: self.argument.swcify(ctx), } } } impl Swcify for swc_estree_ast::JSXElementChild { type Output = swc_ecma_ast::JSXElementChild; fn swcify(self, ctx: &Context) -> Self::Output { match self { swc_estree_ast::JSXElementChild::Text(v) => { swc_ecma_ast::JSXElementChild::JSXText(v.swcify(ctx)) } swc_estree_ast::JSXElementChild::Expr(v) => { swc_ecma_ast::JSXElementChild::from(v.swcify(ctx)) } swc_estree_ast::JSXElementChild::Spread(v) => { swc_ecma_ast::JSXElementChild::from(v.swcify(ctx)) } swc_estree_ast::JSXElementChild::Element(v) => { swc_ecma_ast::JSXElementChild::from(Box::new(v.swcify(ctx))) } swc_estree_ast::JSXElementChild::Fragment(v) => { swc_ecma_ast::JSXElementChild::from(v.swcify(ctx)) } } } } impl Swcify for swc_estree_ast::JSXText { type Output = swc_ecma_ast::JSXText; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::JSXText { span: ctx.span(&self.base), value: self.value, // TODO fix me raw: Default::default(), } } } impl Swcify for swc_estree_ast::JSXSpreadChild { type Output = swc_ecma_ast::JSXSpreadChild; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::JSXSpreadChild { span: ctx.span(&self.base), expr: self.expression.swcify(ctx), } } } impl Swcify for swc_estree_ast::JSXClosingElement { type Output = swc_ecma_ast::JSXClosingElement; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::JSXClosingElement { span: ctx.span(&self.base), name: self.name.swcify(ctx), } } } impl Swcify for swc_estree_ast::JSXFragment { type Output = swc_ecma_ast::JSXFragment; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::JSXFragment { span: ctx.span(&self.base), opening: self.opening_fragment.swcify(ctx), children: self.children.swcify(ctx), closing: self.closing_fragment.swcify(ctx), } } } impl Swcify for swc_estree_ast::JSXOpeningFragment { type Output = swc_ecma_ast::JSXOpeningFragment; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::JSXOpeningFragment { span: ctx.span(&self.base), } } } impl Swcify for swc_estree_ast::JSXClosingFragment { type Output = swc_ecma_ast::JSXClosingFragment; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::JSXClosingFragment { span: ctx.span(&self.base), } } } impl Swcify for BindExpression { type Output = Never; fn swcify(self, _: &Context) -> Self::Output { panic!("swc does not support bind expressions") } } impl Swcify for DoExpression { type Output = Never; fn swcify(self, _: &Context) -> Self::Output { panic!("swc does not support do expressions") } } impl Swcify for PipelinePrimaryTopicReference { type Output = Never; fn swcify(self, _: &Context) -> Self::Output { panic!("swc does not support `PipelinePrimaryTopicReference`") } } impl Swcify for RecordExpression { type Output = Never; fn swcify(self, _: &Context) -> Self::Output { panic!("swc does not support record expressions") } } impl Swcify for TupleExpression { type Output = Never; fn swcify(self, _: &Context) -> Self::Output { panic!("swc does not support tuple expressions") } } impl Swcify for ModuleExpression { type Output = Never; fn swcify(self, _: &Context) -> Self::Output { panic!("swc does not support module expressions") } } impl Swcify for TSAsExpression { type Output = TsAsExpr; fn swcify(self, ctx: &Context) -> Self::Output { TsAsExpr { span: ctx.span(&self.base), expr: self.expression.swcify(ctx), type_ann: self.type_annotation.swcify(ctx), } } } impl Swcify for TSTypeAssertion { type Output = TsTypeAssertion; fn swcify(self, ctx: &Context) -> Self::Output { TsTypeAssertion { span: ctx.span(&self.base), expr: self.expression.swcify(ctx), type_ann: self.type_annotation.swcify(ctx), } } } impl Swcify for TSNonNullExpression { type Output = TsNonNullExpr; fn swcify(self, ctx: &Context) -> Self::Output { TsNonNullExpr { span: ctx.span(&self.base), expr: self.expression.swcify(ctx), } } } impl Swcify for ArrayExprEl { type Output = ExprOrSpread; fn swcify(self, ctx: &Context) -> Self::Output { match self { ArrayExprEl::Spread(s) => ExprOrSpread { // TODO: Use correct span spread: Some(ctx.span(&s.base)), expr: s.argument.swcify(ctx), }, ArrayExprEl::Expr(e) => ExprOrSpread { spread: None, expr: e.swcify(ctx), }, } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/swcify/jsx.rs
Rust
use swc_ecma_ast::Ident; use crate::swcify::{Context, Swcify}; impl Swcify for swc_estree_ast::JSXNamespacedName { type Output = swc_ecma_ast::JSXNamespacedName; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::JSXNamespacedName { span: ctx.span(&self.base), ns: self.namespace.swcify(ctx).into(), name: self.name.swcify(ctx).into(), } } } impl Swcify for swc_estree_ast::JSXIdentifier { type Output = Ident; fn swcify(self, ctx: &Context) -> Self::Output { Ident { span: ctx.span(&self.base), sym: self.name, ..Default::default() } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/swcify/lit.rs
Rust
use swc_ecma_ast::{BigInt, Bool, Expr, Lit, Null, Number, Regex, Str, Tpl, TplElement}; use swc_estree_ast::{ BigIntLiteral, BooleanLiteral, DecimalLiteral, Literal, NullLiteral, NumberLiteral, NumericLiteral, RegExpLiteral, StringLiteral, TemplateElement, TemplateLiteral, TemplateLiteralExpr, }; use super::Context; use crate::swcify::Swcify; impl Swcify for Literal { type Output = Lit; fn swcify(self, ctx: &Context) -> Self::Output { match self { Literal::String(v) => v.swcify(ctx).into(), Literal::Numeric(v) => v.swcify(ctx).into(), Literal::Null(v) => v.swcify(ctx).into(), Literal::Boolean(v) => v.swcify(ctx).into(), Literal::RegExp(v) => v.swcify(ctx).into(), Literal::Template(..) => unreachable!(), Literal::BigInt(v) => v.swcify(ctx).into(), Literal::Decimal(v) => v.swcify(ctx).into(), } } } impl Swcify for StringLiteral { type Output = Str; fn swcify(self, ctx: &Context) -> Self::Output { Str { span: ctx.span(&self.base), value: self.value, raw: Some(self.raw), } } } impl Swcify for NumberLiteral { type Output = Number; fn swcify(self, ctx: &Context) -> Self::Output { Number { span: ctx.span(&self.base), value: self.value, // TODO improve me raw: None, } } } impl Swcify for NumericLiteral { type Output = Number; fn swcify(self, ctx: &Context) -> Self::Output { Number { span: ctx.span(&self.base), value: self.value, // TODO improve me raw: None, } } } impl Swcify for NullLiteral { type Output = Null; fn swcify(self, ctx: &Context) -> Self::Output { Null { span: ctx.span(&self.base), } } } impl Swcify for BooleanLiteral { type Output = Bool; fn swcify(self, ctx: &Context) -> Self::Output { Bool { span: ctx.span(&self.base), value: self.value, } } } impl Swcify for RegExpLiteral { type Output = Regex; fn swcify(self, ctx: &Context) -> Self::Output { Regex { span: ctx.span(&self.base), exp: self.pattern, flags: self.flags, } } } impl Swcify for TemplateLiteral { type Output = Tpl; fn swcify(self, ctx: &Context) -> Self::Output { Tpl { span: ctx.span(&self.base), exprs: self.expressions.swcify(ctx), quasis: self.quasis.swcify(ctx), } } } impl Swcify for TemplateLiteralExpr { type Output = Box<Expr>; fn swcify(self, ctx: &Context) -> Self::Output { match self { TemplateLiteralExpr::TSType(..) => todo!(), TemplateLiteralExpr::Expr(v) => v.swcify(ctx), } } } impl Swcify for TemplateElement { type Output = TplElement; fn swcify(self, ctx: &Context) -> Self::Output { TplElement { span: ctx.span(&self.base), tail: self.tail, cooked: self.value.cooked, raw: self.value.raw, } } } impl Swcify for BigIntLiteral { type Output = BigInt; fn swcify(self, ctx: &Context) -> Self::Output { BigInt { span: ctx.span(&self.base), value: self .value .parse() .map(Box::new) .expect("failed to parse the value of BigIntLiteral"), // TODO improve me raw: None, } } } impl Swcify for DecimalLiteral { type Output = Number; fn swcify(self, ctx: &Context) -> Self::Output { Number { span: ctx.span(&self.base), value: self .value .parse() .expect("failed to parse the value of DecimalLiteral"), // TODO improve me raw: None, } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/swcify/mod.rs
Rust
use std::fmt::Debug; pub use self::ctx::Context; mod class; mod ctx; mod expr; mod jsx; mod lit; mod pat; mod program; mod stmt; mod typescript; /// Used to convert a babel ast node to pub trait Swcify { type Output: Debug + Send + Sync; fn swcify(self, ctx: &Context) -> Self::Output; } impl<T> Swcify for Vec<T> where T: Swcify, { type Output = Vec<T::Output>; fn swcify(self, ctx: &Context) -> Self::Output { self.into_iter().map(|v| v.swcify(ctx)).collect() } } impl<T> Swcify for Option<T> where T: Swcify, { type Output = Option<T::Output>; fn swcify(self, ctx: &Context) -> Self::Output { self.map(|v| v.swcify(ctx)) } } impl<T> Swcify for Box<T> where T: Swcify, { type Output = T::Output; fn swcify(self, ctx: &Context) -> Self::Output { (*self).swcify(ctx) } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/swcify/pat.rs
Rust
use swc_common::Spanned; use swc_ecma_ast::*; use swc_estree_ast::{ ArrayPattern, AssignmentPattern, AssignmentPatternLeft, LVal, ObjectPattern, ObjectPatternProp, PatternLike, RestElement, }; use crate::swcify::{Context, Swcify}; impl Swcify for LVal { type Output = Pat; fn swcify(self, ctx: &Context) -> Self::Output { match self { LVal::Id(i) => i.swcify(ctx).into(), LVal::MemberExpr(e) => Box::new(e.swcify(ctx)).into(), LVal::RestEl(e) => e.swcify(ctx).into(), LVal::AssignmentPat(e) => e.swcify(ctx).into(), LVal::ArrayPat(e) => e.swcify(ctx).into(), LVal::ObjectPat(e) => e.swcify(ctx).into(), LVal::TSParamProp(..) => todo!(), } } } impl Swcify for RestElement { type Output = RestPat; fn swcify(self, ctx: &Context) -> Self::Output { let span = ctx.span(&self.base); RestPat { span, dot3_token: span, arg: Box::new(self.argument.swcify(ctx)), type_ann: None, } } } impl Swcify for AssignmentPattern { type Output = AssignPat; fn swcify(self, ctx: &Context) -> Self::Output { AssignPat { span: ctx.span(&self.base), left: Box::new(self.left.swcify(ctx)), right: self.right.swcify(ctx), } } } impl Swcify for AssignmentPatternLeft { type Output = Pat; fn swcify(self, ctx: &Context) -> Self::Output { match self { AssignmentPatternLeft::Id(v) => v.swcify(ctx).into(), AssignmentPatternLeft::Object(v) => v.swcify(ctx).into(), AssignmentPatternLeft::Array(v) => v.swcify(ctx).into(), AssignmentPatternLeft::Member(v) => Box::new(v.swcify(ctx)).into(), } } } impl Swcify for ArrayPattern { type Output = ArrayPat; fn swcify(self, ctx: &Context) -> Self::Output { ArrayPat { span: ctx.span(&self.base), elems: self.elements.swcify(ctx), optional: false, type_ann: None, } } } impl Swcify for PatternLike { type Output = Pat; fn swcify(self, ctx: &Context) -> Self::Output { match self { PatternLike::Id(v) => v.swcify(ctx).into(), PatternLike::RestEl(v) => v.swcify(ctx).into(), PatternLike::AssignmentPat(v) => v.swcify(ctx).into(), PatternLike::ArrayPat(v) => v.swcify(ctx).into(), PatternLike::ObjectPat(v) => v.swcify(ctx).into(), } } } impl Swcify for ObjectPattern { type Output = ObjectPat; fn swcify(self, ctx: &Context) -> Self::Output { ObjectPat { span: ctx.span(&self.base), props: self.properties.swcify(ctx), optional: false, type_ann: None, } } } impl Swcify for ObjectPatternProp { type Output = ObjectPatProp; fn swcify(self, ctx: &Context) -> Self::Output { match self { ObjectPatternProp::Rest(v) => ObjectPatProp::Rest(v.swcify(ctx)), ObjectPatternProp::Prop(prop) => { if prop.shorthand { return ObjectPatProp::Assign(AssignPatProp { span: ctx.span(&prop.base), key: prop.key.swcify(ctx).expect_ident().into(), value: None, }); } match prop.value { swc_estree_ast::ObjectPropVal::Pattern(v) => { ObjectPatProp::KeyValue(KeyValuePatProp { key: prop.key.swcify(ctx), value: Box::new(v.swcify(ctx)), }) } swc_estree_ast::ObjectPropVal::Expr(v) => { ObjectPatProp::Assign(AssignPatProp { span: ctx.span(&prop.base), key: prop.key.swcify(ctx).expect_ident().into(), value: Some(v.swcify(ctx)), }) } } } } } } impl Swcify for swc_estree_ast::Pattern { type Output = Pat; fn swcify(self, ctx: &Context) -> Self::Output { match self { swc_estree_ast::Pattern::Assignment(v) => v.swcify(ctx).into(), swc_estree_ast::Pattern::Array(v) => v.swcify(ctx).into(), swc_estree_ast::Pattern::Object(v) => v.swcify(ctx).into(), } } } impl Swcify for swc_estree_ast::Param { type Output = swc_ecma_ast::Param; fn swcify(self, ctx: &Context) -> Self::Output { match self { swc_estree_ast::Param::Id(v) => { let pat = v.swcify(ctx); swc_ecma_ast::Param { span: pat.span(), decorators: Default::default(), pat: pat.into(), } } swc_estree_ast::Param::Pat(v) => { let pat = v.swcify(ctx); swc_ecma_ast::Param { span: pat.span(), decorators: Default::default(), pat, } } swc_estree_ast::Param::Rest(v) => swc_ecma_ast::Param { span: ctx.span(&v.base), decorators: v.decorators.swcify(ctx).unwrap_or_default(), pat: v.argument.swcify(ctx), }, swc_estree_ast::Param::TSProp(..) => todo!(), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/swcify/program.rs
Rust
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/swcify/stmt.rs
Rust
use swc_common::DUMMY_SP; use swc_ecma_ast::{ BlockStmt, BreakStmt, ClassDecl, ClassExpr, ContinueStmt, DebuggerStmt, DefaultDecl, DoWhileStmt, EmptyStmt, ExportAll, ExportDecl, ExportDefaultDecl, ExportDefaultExpr, ExportNamedSpecifier, ExprStmt, FnDecl, FnExpr, ForHead, ForInStmt, ForOfStmt, ForStmt, IfStmt, ImportDecl, ImportNamedSpecifier, ImportSpecifier, ImportStarAsSpecifier, KeyValueProp, LabeledStmt, Lit, ModuleDecl, ModuleItem, NamedExport, ObjectLit, Pat, Prop, PropName, PropOrSpread, ReturnStmt, SwitchStmt, ThrowStmt, TryStmt, TsExportAssignment, TsInterfaceDecl, TsModuleDecl, TsTypeAliasDecl, VarDecl, VarDeclKind, VarDeclOrExpr, VarDeclarator, WhileStmt, WithStmt, }; use swc_estree_ast::{ BlockStatement, BreakStatement, ClassDeclaration, ContinueStatement, DebuggerStatement, DeclareClass, DeclareExportAllDeclaration, DeclareExportDeclaration, DeclareFunction, DeclareInterface, DeclareModule, DeclareModuleExports, DeclareTypeAlias, DeclareVariable, DoWhileStatement, EmptyStatement, ExportAllDeclaration, ExportDefaultDeclType, ExportDefaultDeclaration, ExportKind, ExportNamedDeclaration, ExpressionStatement, ForInStatement, ForOfStatement, ForStatement, ForStmtInit, ForStmtLeft, FunctionDeclaration, IdOrString, IfStatement, ImportAttribute, ImportDeclaration, ImportKind, ImportNamespaceSpecifier, ImportSpecifierType, LabeledStatement, ReturnStatement, Statement, SwitchStatement, ThrowStatement, TryStatement, VariableDeclaration, VariableDeclarationKind, VariableDeclarator, WhileStatement, WithStatement, }; use super::Context; use crate::swcify::Swcify; impl Swcify for BlockStatement { type Output = BlockStmt; fn swcify(self, ctx: &Context) -> Self::Output { BlockStmt { span: ctx.span(&self.base), stmts: self .body .swcify(ctx) .into_iter() .map(|v| v.expect_stmt()) .collect(), ..Default::default() } } } impl Swcify for Statement { type Output = ModuleItem; fn swcify(self, ctx: &Context) -> Self::Output { match self { Statement::Block(v) => v.swcify(ctx).into(), Statement::Break(v) => v.swcify(ctx).into(), Statement::Continue(v) => v.swcify(ctx).into(), Statement::Debugger(v) => v.swcify(ctx).into(), Statement::DoWhile(v) => v.swcify(ctx).into(), Statement::Empty(v) => v.swcify(ctx).into(), Statement::Expr(v) => v.swcify(ctx).into(), Statement::ForIn(v) => v.swcify(ctx).into(), Statement::For(v) => v.swcify(ctx).into(), Statement::FuncDecl(v) => v.swcify(ctx).into(), Statement::If(v) => v.swcify(ctx).into(), Statement::Labeled(v) => v.swcify(ctx).into(), Statement::Return(v) => v.swcify(ctx).into(), Statement::Switch(v) => v.swcify(ctx).into(), Statement::Throw(v) => v.swcify(ctx).into(), Statement::Try(v) => v.swcify(ctx).into(), Statement::VarDecl(v) => v.swcify(ctx).into(), Statement::While(v) => v.swcify(ctx).into(), Statement::With(v) => v.swcify(ctx).into(), Statement::ClassDecl(v) => v.swcify(ctx).into(), Statement::ExportAllDecl(v) => ModuleItem::ModuleDecl(v.swcify(ctx).into()), Statement::ExportDefaultDecl(v) => ModuleItem::ModuleDecl(v.swcify(ctx)), Statement::ExportNamedDecl(v) => ModuleItem::ModuleDecl(v.swcify(ctx).into()), Statement::ForOf(v) => v.swcify(ctx).into(), Statement::ImportDecl(v) => ModuleItem::ModuleDecl(v.swcify(ctx).into()), Statement::DeclClass(v) => v.swcify(ctx).into(), Statement::DeclFunc(v) => v.swcify(ctx).into(), Statement::DeclInterface(v) => v.swcify(ctx).into(), Statement::DeclModule(v) => v.swcify(ctx).into(), Statement::DeclareModuleExports(v) => ModuleItem::ModuleDecl(v.swcify(ctx).into()), Statement::DeclTypeAlias(v) => v.swcify(ctx).into(), Statement::DeclVar(v) => v.swcify(ctx).into(), Statement::DeclExportDeclaration(v) => ModuleItem::ModuleDecl(v.swcify(ctx).into()), Statement::DeclExportAllDeclaration(v) => ModuleItem::ModuleDecl(v.swcify(ctx).into()), _ => { todo!("swcify: {:?}", self) } } } } impl Swcify for BreakStatement { type Output = BreakStmt; fn swcify(self, ctx: &Context) -> Self::Output { BreakStmt { span: ctx.span(&self.base), label: self.label.swcify(ctx).map(|v| v.into()), } } } impl Swcify for ContinueStatement { type Output = ContinueStmt; fn swcify(self, ctx: &Context) -> Self::Output { ContinueStmt { span: ctx.span(&self.base), label: self.label.swcify(ctx).map(|v| v.into()), } } } impl Swcify for DebuggerStatement { type Output = DebuggerStmt; fn swcify(self, ctx: &Context) -> Self::Output { DebuggerStmt { span: ctx.span(&self.base), } } } impl Swcify for DoWhileStatement { type Output = DoWhileStmt; fn swcify(self, ctx: &Context) -> Self::Output { DoWhileStmt { span: ctx.span(&self.base), test: self.test.swcify(ctx), body: Box::new(self.body.swcify(ctx).expect_stmt()), } } } impl Swcify for EmptyStatement { type Output = EmptyStmt; fn swcify(self, ctx: &Context) -> Self::Output { EmptyStmt { span: ctx.span(&self.base), } } } impl Swcify for ExpressionStatement { type Output = ExprStmt; fn swcify(self, ctx: &Context) -> Self::Output { ExprStmt { span: ctx.span(&self.base), expr: self.expression.swcify(ctx), } } } impl Swcify for ForInStatement { type Output = ForInStmt; fn swcify(self, ctx: &Context) -> Self::Output { ForInStmt { span: ctx.span(&self.base), left: self.left.swcify(ctx), right: self.right.swcify(ctx), body: Box::new(self.body.swcify(ctx).expect_stmt()), } } } impl Swcify for ForStmtLeft { type Output = ForHead; fn swcify(self, ctx: &Context) -> Self::Output { match self { ForStmtLeft::VarDecl(v) => ForHead::VarDecl(v.swcify(ctx).into()), ForStmtLeft::LVal(v) => ForHead::Pat(v.swcify(ctx).into()), } } } impl Swcify for ForStatement { type Output = ForStmt; fn swcify(self, ctx: &Context) -> Self::Output { ForStmt { span: ctx.span(&self.base), init: self.init.swcify(ctx), test: self.test.swcify(ctx), update: self.update.swcify(ctx), body: Box::new(self.body.swcify(ctx).expect_stmt()), } } } impl Swcify for ForStmtInit { type Output = VarDeclOrExpr; fn swcify(self, ctx: &Context) -> Self::Output { match self { ForStmtInit::VarDecl(v) => VarDeclOrExpr::VarDecl(v.swcify(ctx).into()), ForStmtInit::Expr(v) => VarDeclOrExpr::Expr(v.swcify(ctx)), } } } impl Swcify for FunctionDeclaration { type Output = FnDecl; fn swcify(self, ctx: &Context) -> Self::Output { FnDecl { ident: self.id.swcify(ctx).map(|v| v.into()).unwrap(), declare: false, function: swc_ecma_ast::Function { params: self.params.swcify(ctx), decorators: Default::default(), span: ctx.span(&self.base), body: Some(self.body.swcify(ctx)), is_generator: false, is_async: self.is_async.unwrap_or_default(), ..Default::default() } .into(), } } } impl Swcify for IfStatement { type Output = IfStmt; fn swcify(self, ctx: &Context) -> Self::Output { IfStmt { span: ctx.span(&self.base), test: self.test.swcify(ctx), cons: Box::new(self.consequent.swcify(ctx).expect_stmt()), alt: self .alternate .swcify(ctx) .map(|v| v.expect_stmt()) .map(Box::new), } } } impl Swcify for LabeledStatement { type Output = LabeledStmt; fn swcify(self, ctx: &Context) -> Self::Output { LabeledStmt { span: ctx.span(&self.base), label: self.label.swcify(ctx).into(), body: Box::new(self.body.swcify(ctx).expect_stmt()), } } } impl Swcify for ReturnStatement { type Output = ReturnStmt; fn swcify(self, ctx: &Context) -> Self::Output { ReturnStmt { span: ctx.span(&self.base), arg: self.argument.swcify(ctx), } } } impl Swcify for SwitchStatement { type Output = SwitchStmt; fn swcify(self, ctx: &Context) -> Self::Output { SwitchStmt { span: ctx.span(&self.base), discriminant: self.discriminant.swcify(ctx), cases: self.cases.swcify(ctx), } } } impl Swcify for swc_estree_ast::SwitchCase { type Output = swc_ecma_ast::SwitchCase; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::SwitchCase { span: ctx.span(&self.base), test: self.test.swcify(ctx), cons: self .consequent .swcify(ctx) .into_iter() .map(|v| v.expect_stmt()) .collect(), } } } impl Swcify for ThrowStatement { type Output = ThrowStmt; fn swcify(self, ctx: &Context) -> Self::Output { ThrowStmt { span: ctx.span(&self.base), arg: self.argument.swcify(ctx), } } } impl Swcify for TryStatement { type Output = TryStmt; fn swcify(self, ctx: &Context) -> Self::Output { TryStmt { span: ctx.span(&self.base), block: self.block.swcify(ctx), handler: self.handler.swcify(ctx), finalizer: self.finalizer.swcify(ctx), } } } impl Swcify for swc_estree_ast::CatchClause { type Output = swc_ecma_ast::CatchClause; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::CatchClause { span: ctx.span(&self.base), param: self.param.swcify(ctx), body: self.body.swcify(ctx), } } } impl Swcify for swc_estree_ast::CatchClauseParam { type Output = Pat; fn swcify(self, ctx: &Context) -> Self::Output { match self { swc_estree_ast::CatchClauseParam::Id(v) => v.swcify(ctx).into(), swc_estree_ast::CatchClauseParam::Array(v) => v.swcify(ctx).into(), swc_estree_ast::CatchClauseParam::Object(v) => v.swcify(ctx).into(), } } } impl Swcify for VariableDeclaration { type Output = VarDecl; fn swcify(self, ctx: &Context) -> Self::Output { VarDecl { span: ctx.span(&self.base), kind: match self.kind { VariableDeclarationKind::Var => VarDeclKind::Var, VariableDeclarationKind::Let => VarDeclKind::Let, VariableDeclarationKind::Const => VarDeclKind::Const, }, declare: self.declare.unwrap_or_default(), decls: self.declarations.swcify(ctx), ..Default::default() } } } impl Swcify for VariableDeclarator { type Output = VarDeclarator; fn swcify(self, ctx: &Context) -> Self::Output { VarDeclarator { span: ctx.span(&self.base), name: self.id.swcify(ctx), init: self.init.swcify(ctx), definite: self.definite.unwrap_or_default(), } } } impl Swcify for WhileStatement { type Output = WhileStmt; fn swcify(self, ctx: &Context) -> Self::Output { WhileStmt { span: ctx.span(&self.base), test: self.test.swcify(ctx), body: Box::new(self.body.swcify(ctx).expect_stmt()), } } } impl Swcify for WithStatement { type Output = WithStmt; fn swcify(self, ctx: &Context) -> Self::Output { WithStmt { span: ctx.span(&self.base), obj: self.object.swcify(ctx), body: Box::new(self.body.swcify(ctx).expect_stmt()), } } } impl Swcify for ClassDeclaration { type Output = ClassDecl; fn swcify(self, ctx: &Context) -> Self::Output { ClassDecl { ident: self.id.swcify(ctx).into(), declare: self.declare.unwrap_or_default(), class: swc_ecma_ast::Class { span: ctx.span(&self.base), decorators: self.decorators.swcify(ctx).unwrap_or_default(), body: self.body.swcify(ctx), super_class: self.super_class.swcify(ctx), is_abstract: self.is_abstract.unwrap_or_default(), ..Default::default() } .into(), } } } impl Swcify for ExportAllDeclaration { type Output = ExportAll; fn swcify(self, ctx: &Context) -> Self::Output { ExportAll { span: ctx.span(&self.base), src: self.source.swcify(ctx).into(), type_only: self.export_kind == Some(ExportKind::Type), with: self .with .swcify(ctx) .map(|props| { props .into_iter() .map(Prop::KeyValue) .map(Box::new) .map(PropOrSpread::Prop) .collect() }) .map(|props| { ObjectLit { span: DUMMY_SP, props, } .into() }), } } } impl Swcify for ImportAttribute { type Output = KeyValueProp; fn swcify(self, ctx: &Context) -> Self::Output { KeyValueProp { key: self.key.swcify(ctx), value: Lit::Str(self.value.swcify(ctx)).into(), } } } impl Swcify for IdOrString { type Output = PropName; fn swcify(self, ctx: &Context) -> Self::Output { match self { IdOrString::Id(v) => PropName::Ident(v.swcify(ctx).into()), IdOrString::String(v) => PropName::Str(v.swcify(ctx)), } } } impl Swcify for ExportDefaultDeclaration { type Output = ModuleDecl; fn swcify(self, ctx: &Context) -> Self::Output { match self.declaration { ExportDefaultDeclType::Func(v) => { let d = v.swcify(ctx); ExportDefaultDecl { span: ctx.span(&self.base), decl: DefaultDecl::Fn(FnExpr { ident: Some(d.ident), function: d.function, }), } .into() } ExportDefaultDeclType::Class(v) => { let d = v.swcify(ctx); ExportDefaultDecl { span: ctx.span(&self.base), decl: DefaultDecl::Class(ClassExpr { ident: Some(d.ident), class: d.class, }), } .into() } ExportDefaultDeclType::Expr(v) => ExportDefaultExpr { span: ctx.span(&self.base), expr: v.swcify(ctx), } .into(), _ => { todo!("swcify: {:?}", self) } } } } impl Swcify for ExportNamedDeclaration { type Output = NamedExport; fn swcify(self, ctx: &Context) -> Self::Output { NamedExport { span: ctx.span(&self.base), specifiers: self.specifiers.swcify(ctx), src: self.source.swcify(ctx).map(Box::new), type_only: false, with: self .with .swcify(ctx) .map(|props| { props .into_iter() .map(Prop::KeyValue) .map(Box::new) .map(PropOrSpread::Prop) .collect() }) .map(|props| { ObjectLit { span: DUMMY_SP, props, } .into() }), } } } impl Swcify for swc_estree_ast::ExportSpecifierType { type Output = swc_ecma_ast::ExportSpecifier; fn swcify(self, ctx: &Context) -> Self::Output { match self { swc_estree_ast::ExportSpecifierType::Export(v) => { swc_ecma_ast::ExportSpecifier::from(v.swcify(ctx)) } swc_estree_ast::ExportSpecifierType::Default(v) => { swc_ecma_ast::ExportSpecifier::from(v.swcify(ctx)) } swc_estree_ast::ExportSpecifierType::Namespace(v) => { swc_ecma_ast::ExportSpecifier::from(v.swcify(ctx)) } } } } impl Swcify for swc_estree_ast::ExportSpecifier { type Output = ExportNamedSpecifier; fn swcify(self, ctx: &Context) -> Self::Output { ExportNamedSpecifier { span: ctx.span(&self.base), orig: self.local.swcify(ctx), exported: Some(self.exported.swcify(ctx)), is_type_only: matches!(self.export_kind, ExportKind::Type), } } } impl Swcify for swc_estree_ast::ExportDefaultSpecifier { type Output = swc_ecma_ast::ExportDefaultSpecifier; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::ExportDefaultSpecifier { exported: self.exported.swcify(ctx).into(), } } } impl Swcify for swc_estree_ast::ExportNamespaceSpecifier { type Output = swc_ecma_ast::ExportNamespaceSpecifier; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::ExportNamespaceSpecifier { span: ctx.span(&self.base), name: self.exported.swcify(ctx), } } } impl Swcify for ForOfStatement { type Output = ForOfStmt; fn swcify(self, ctx: &Context) -> Self::Output { ForOfStmt { span: ctx.span(&self.base), is_await: false, left: self.left.swcify(ctx), right: self.right.swcify(ctx), body: Box::new(self.body.swcify(ctx).expect_stmt()), } } } impl Swcify for ImportDeclaration { type Output = ImportDecl; fn swcify(self, ctx: &Context) -> Self::Output { ImportDecl { span: ctx.span(&self.base), specifiers: self.specifiers.swcify(ctx), src: self.source.swcify(ctx).into(), type_only: false, with: self .with .swcify(ctx) .map(|props| { props .into_iter() .map(Prop::KeyValue) .map(Box::new) .map(PropOrSpread::Prop) .collect() }) .map(|props| { ObjectLit { span: DUMMY_SP, props, } .into() }), phase: self .phase .map(|phase| Swcify::swcify(phase, ctx)) .unwrap_or_default(), } } } impl Swcify for swc_estree_ast::ImportPhase { type Output = swc_ecma_ast::ImportPhase; fn swcify(self, _: &Context) -> Self::Output { match self { Self::Source => Self::Output::Source, Self::Defer => Self::Output::Defer, } } } impl Swcify for ImportSpecifierType { type Output = ImportSpecifier; fn swcify(self, ctx: &Context) -> Self::Output { match self { ImportSpecifierType::Import(v) => v.swcify(ctx).into(), ImportSpecifierType::Default(v) => v.swcify(ctx).into(), ImportSpecifierType::Namespace(v) => v.swcify(ctx).into(), } } } impl Swcify for swc_estree_ast::ModuleExportNameType { type Output = swc_ecma_ast::ModuleExportName; fn swcify(self, ctx: &Context) -> Self::Output { match self { swc_estree_ast::ModuleExportNameType::Ident(ident) => { swc_ecma_ast::ModuleExportName::Ident(ident.swcify(ctx).into()) } swc_estree_ast::ModuleExportNameType::Str(s) => s.swcify(ctx).into(), } } } impl Swcify for swc_estree_ast::ImportSpecifier { type Output = ImportNamedSpecifier; fn swcify(self, ctx: &Context) -> Self::Output { ImportNamedSpecifier { span: ctx.span(&self.base), local: self.local.swcify(ctx).into(), imported: Some(self.imported.swcify(ctx)), is_type_only: matches!(self.import_kind, Some(ImportKind::Type)), } } } impl Swcify for swc_estree_ast::ImportDefaultSpecifier { type Output = swc_ecma_ast::ImportDefaultSpecifier; fn swcify(self, ctx: &Context) -> Self::Output { swc_ecma_ast::ImportDefaultSpecifier { span: ctx.span(&self.base), local: self.local.swcify(ctx).into(), } } } impl Swcify for ImportNamespaceSpecifier { type Output = ImportStarAsSpecifier; fn swcify(self, ctx: &Context) -> Self::Output { ImportStarAsSpecifier { span: ctx.span(&self.base), local: self.local.swcify(ctx).into(), } } } impl Swcify for DeclareClass { type Output = ClassDecl; fn swcify(self, _: &Context) -> Self::Output { unimplemented!("flow") } } impl Swcify for DeclareFunction { type Output = FnDecl; fn swcify(self, _: &Context) -> Self::Output { unimplemented!("flow") } } impl Swcify for DeclareInterface { type Output = TsInterfaceDecl; fn swcify(self, _: &Context) -> Self::Output { unimplemented!("flow") } } impl Swcify for DeclareModule { type Output = TsModuleDecl; fn swcify(self, _: &Context) -> Self::Output { unimplemented!("flow") } } impl Swcify for DeclareModuleExports { type Output = TsExportAssignment; fn swcify(self, _: &Context) -> Self::Output { unimplemented!("flow") } } impl Swcify for DeclareTypeAlias { type Output = TsTypeAliasDecl; fn swcify(self, _: &Context) -> Self::Output { unimplemented!("flow") } } impl Swcify for DeclareVariable { type Output = VarDecl; fn swcify(self, _: &Context) -> Self::Output { unimplemented!("flow") } } impl Swcify for DeclareExportDeclaration { type Output = ExportDecl; fn swcify(self, _: &Context) -> Self::Output { unimplemented!("flow") } } impl Swcify for DeclareExportAllDeclaration { type Output = ExportAll; fn swcify(self, ctx: &Context) -> Self::Output { ExportAll { span: ctx.span(&self.base), src: self.source.swcify(ctx).into(), type_only: self.export_kind == Some(ExportKind::Type), with: Default::default(), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/src/swcify/typescript.rs
Rust
use swc_ecma_ast::{ Accessibility, Ident, TsEntityName, TsQualifiedName, TsType, TsTypeAnn, TsTypeParam, TsTypeParamDecl, TsTypeParamInstantiation, }; use swc_estree_ast::{ Access, FlowType, SuperTypeParams, TSEntityName, TSQualifiedName, TSType, TSTypeAnnotation, TSTypeParameter, TSTypeParameterDeclaration, TSTypeParameterInstantiation, TypeAnnotOrNoop, TypeParamDeclOrNoop, }; use super::Context; use crate::{swcify::Swcify, Never}; impl Swcify for TSTypeParameterInstantiation { type Output = TsTypeParamInstantiation; fn swcify(self, ctx: &Context) -> Self::Output { TsTypeParamInstantiation { span: ctx.span(&self.base), params: self.params.swcify(ctx), } } } impl Swcify for FlowType { type Output = Never; fn swcify(self, _: &Context) -> Self::Output { unreachable!("swc does not support flow types") } } impl Swcify for TypeParamDeclOrNoop { type Output = Option<TsTypeParamDecl>; fn swcify(self, ctx: &Context) -> Self::Output { match self { TypeParamDeclOrNoop::Flow(_) => None, TypeParamDeclOrNoop::TS(v) => Some(v.swcify(ctx)), TypeParamDeclOrNoop::Noop(_) => None, } } } impl Swcify for TSTypeParameterDeclaration { type Output = TsTypeParamDecl; fn swcify(self, ctx: &Context) -> Self::Output { TsTypeParamDecl { span: ctx.span(&self.base), params: self.params.swcify(ctx), } } } impl Swcify for TSTypeParameter { type Output = TsTypeParam; fn swcify(self, ctx: &Context) -> Self::Output { let span = ctx.span(&self.base); TsTypeParam { span, name: Ident::new_no_ctxt(self.name, span), is_in: self.is_in, is_out: self.is_out, is_const: self.is_const, constraint: self.constraint.swcify(ctx), default: self.default.swcify(ctx), } } } impl Swcify for TypeAnnotOrNoop { type Output = Option<TsTypeAnn>; fn swcify(self, ctx: &Context) -> Self::Output { match self { TypeAnnotOrNoop::Flow(_) => None, TypeAnnotOrNoop::TS(v) => Some(v.swcify(ctx)), TypeAnnotOrNoop::Noop(_) => None, } } } impl Swcify for TSTypeAnnotation { type Output = TsTypeAnn; fn swcify(self, ctx: &Context) -> Self::Output { TsTypeAnn { span: ctx.span(&self.base), type_ann: self.type_annotation.swcify(ctx), } } } impl Swcify for TSType { type Output = Box<TsType>; fn swcify(self, _: &Context) -> Self::Output { todo!("swc currently does not support importing typescript module from babel") } } impl Swcify for SuperTypeParams { type Output = TsTypeParamInstantiation; fn swcify(self, ctx: &Context) -> Self::Output { match self { SuperTypeParams::Flow(_) => unimplemented!("flow type"), SuperTypeParams::TS(v) => v.swcify(ctx), } } } impl Swcify for Access { type Output = Accessibility; fn swcify(self, _: &Context) -> Self::Output { match self { Access::Public => Accessibility::Public, Access::Private => Accessibility::Private, Access::Protected => Accessibility::Protected, } } } impl Swcify for TSEntityName { type Output = TsEntityName; fn swcify(self, ctx: &Context) -> Self::Output { match self { TSEntityName::Id(v) => TsEntityName::Ident(v.swcify(ctx).into()), TSEntityName::Qualified(v) => TsEntityName::TsQualifiedName(Box::new(v.swcify(ctx))), } } } impl Swcify for TSQualifiedName { type Output = TsQualifiedName; fn swcify(self, ctx: &Context) -> Self::Output { TsQualifiedName { span: ctx.span(&self.base), left: self.left.swcify(ctx), right: self.right.swcify(ctx).into(), } } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/tests/babelgen.js
JavaScript
// Helper for generating Babel fixture JSON. // USAGE: node babelgen.js path/to/input.js > path/to/output.json const {readFileSync} = require("fs"); const {parse} = require("@babel/parser"); const inputFile = process.argv[2]; if (!inputFile) { console.error("Missing input file. Hint: `node babelgen.js path/to/input.js`"); process.exit(1); } const code = readFileSync(inputFile, "utf8"); const plugins = ["classProperties", "classStaticBlocks"]; if (inputFile && inputFile.endsWith(".jsx")) { plugins.push("jsx"); } if (inputFile && inputFile.endsWith(".ts")) { plugins.push("typescript"); } const babelAst = parse(code, { plugins, sourceType: inputFile.endsWith(".mjs") ? "module" : undefined, // allowImportExportEverywhere: true, }); console.log(JSON.stringify(babelAst, null, 4));
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/tests/compare.sh
Shell
#!/usr/bin/env bash # Print a side by side comparison of Babel and SWC AST. SCRIPT_DIR=`dirname "$0"` paste <(node "$SCRIPT_DIR/babelgen.js" $1) <(node "$SCRIPT_DIR/swcgen.js" $1) | column -s $'\t' -t
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/tests/convert.rs
Rust
#![feature(test)] extern crate test; use std::{ env, fs, path::{Path, PathBuf}, sync::Arc, }; use anyhow::{Context as AnyhowContext, Error}; use copyless::BoxHelper; use pretty_assertions::assert_eq; use serde_json::{Number, Value}; use swc::{config::IsModule, Compiler}; use swc_common::{ errors::{ColorConfig, Handler}, FileName, FilePathMapping, SourceMap, GLOBALS, }; use swc_ecma_parser::{EsSyntax, Syntax}; use swc_estree_compat::babelify::{Babelify, Context}; use test::{test_main, DynTestFn, ShouldPanic, TestDesc, TestDescAndFn, TestName, TestType}; use testing::{json::diff_json_value, DebugUsingDisplay}; use walkdir::WalkDir; #[test] fn fixtures() -> Result<(), Error> { let mut tests = Vec::new(); let fixtures_path = PathBuf::from("tests").join("fixtures"); for entry in WalkDir::new(&fixtures_path).into_iter() { let entry = entry.with_context(|| "Failed to walk dir")?; if !entry.file_type().is_dir() { continue; } let js_path: PathBuf = entry.path().join("input.js"); let ts_path: PathBuf = entry.path().join("input.ts"); let mjs_path: PathBuf = entry.path().join("input.mjs"); let jsx_path: PathBuf = entry.path().join("input.jsx"); let output_path: PathBuf = entry.path().join("output.json"); let is_javascript = js_path.is_file(); let is_typescript = ts_path.is_file(); let is_module = mjs_path.is_file(); let is_jsx = jsx_path.is_file(); if (!is_javascript && !is_typescript && !is_module && !is_jsx) || !output_path.is_file() { continue; } let input_path = if is_typescript { &ts_path } else if is_module { &mjs_path } else if is_jsx { &jsx_path } else { &js_path }; let input = fs::read_to_string(input_path) .with_context(|| format!("Failed to open file: {}", &js_path.to_string_lossy()))?; let output = fs::read_to_string(&output_path) .with_context(|| format!("Failed to open file: {}", &output_path.to_string_lossy()))?; tests.push(TestDescAndFn { desc: TestDesc { test_type: TestType::IntegrationTest, name: TestName::DynTestName(format!( "babel_compat::convert::{}", get_test_name(entry.path(), &fixtures_path)? )), ignore: false, should_panic: ShouldPanic::No, compile_fail: false, no_run: false, ignore_message: Default::default(), source_file: Default::default(), start_line: 0, start_col: 0, end_line: 0, end_col: 0, }, testfn: DynTestFn(Box::alloc().init(move || { GLOBALS.set(&Default::default(), || { let syntax = if is_typescript { Syntax::Typescript(Default::default()) } else if is_jsx { Syntax::Es(EsSyntax { jsx: true, ..Default::default() }) } else { Syntax::Es(Default::default()) }; run_test(input, output, syntax, is_module); Ok(()) }) })), }) } test_main( &env::args().collect::<Vec<_>>(), tests, Some(test::Options::new()), ); Ok(()) } // #[test] // fn single_fixture() -> Result<(), Error> { // let input_file = "tests/fixtures/ts-function/input.ts"; // let output_file = "tests/fixtures/ts-function/output.json"; // let input = fs::read_to_string(&input_file) // .with_context(|| format!("Failed to open file: {}", &input_file))?; // let output = fs::read_to_string(&output_file) // .with_context(|| format!("Failed to open file: {}", &output_file))?; // // run_test(input, output, Syntax::default(), false); // // let syntax = Syntax::Es(EsConfig { // // jsx: false, // // ..Default::default() // // }); // let syntax = Syntax::Typescript(Default::default()); // run_test(input, output, syntax, false); // Ok(()) // } fn run_test(src: String, expected: String, syntax: Syntax, is_module: bool) { let cm = Arc::new(SourceMap::new(FilePathMapping::empty())); let handler = Arc::new(Handler::with_tty_emitter( ColorConfig::Always, true, false, Some(cm.clone()), )); let compiler = Compiler::new(cm.clone()); let fm = compiler.cm.new_source_file(FileName::Anon.into(), src); let comments = compiler.comments().clone(); let swc_ast = compiler .parse_js( fm.clone(), &handler, Default::default(), // EsVersion (ES version) syntax, IsModule::Bool(is_module), Some(&comments), ) .unwrap(); let ctx = Context { fm, cm, comments: compiler.comments().clone(), }; let ast = swc_ast.babelify(&ctx); let mut actual = serde_json::to_value(&ast).unwrap(); println!( "Actual: \n{}", serde_json::to_string_pretty(&actual).unwrap() ); let mut expected: Value = serde_json::from_str(&expected).unwrap(); diff_json_value(&mut actual, &mut expected, &mut |k, v| match k { "identifierName" | "extra" | "errors" => { // Remove *v = Value::Null; } "optional" | "computed" | "static" | "abstract" | "declare" | "definite" | "generator" | "readonly" | "expression" => { // TODO(kdy1): Remove this if let Value::Bool(false) = v { *v = Value::Null; } } "decorators" | "implements" => { // TODO(kdy1): Remove this if let Value::Array(arr) = v { if arr.is_empty() { *v = Value::Null; } } } "sourceFile" => { // TODO(kdy1): Remove this if let Value::String(s) = v { if s.is_empty() { *v = Value::Null; } } } "value" => { // Normalize numbers match v { Value::Number(n) => { *n = Number::from_f64(n.as_f64().unwrap()).unwrap(); } Value::String(s) => { // TODO(kdy1): Remove this // This is wrong, but we are not babel ast at the moment *s = s.replace('\n', ""); } _ => {} } } "raw" => { // TODO fix me // Remove *v = Value::Null; } _ => {} }); let actual = serde_json::to_string_pretty(&actual).unwrap(); let expected = serde_json::to_string_pretty(&expected).unwrap(); assert_eq!(DebugUsingDisplay(&actual), DebugUsingDisplay(&expected)); } fn get_test_name(path: &Path, fixture_path: &Path) -> Result<String, Error> { let s: String = path.strip_prefix(fixture_path)?.to_string_lossy().into(); Ok(s) }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/tests/fixtures/array-destructuring/input.js
JavaScript
const arr = [ 1, 2, 3 ]; const [ a, b, ...other ] = arr;
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/tests/fixtures/array-simple/input.js
JavaScript
const arr = [ 1, 2, 3 ];
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/tests/fixtures/class-extends/input.js
JavaScript
class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a noise.`); } } class Dog extends Animal { constructor(name) { super(name); } speak() { console.log(`${this.name} barks.`); } }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/tests/fixtures/class-getter-setter/input.js
JavaScript
class Rectangle { constructor(height, width) { this.height = height; this.width = width; } set height(height) { this.height = height; } set width(width) { this.width = width; } get area() { return this.calcArea(); } calcArea() { return this.height * this.width; } } const square = new Rectangle(10, 10); console.log(square.area);
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University
crates/swc_estree_compat/tests/fixtures/class-method-no-body/input.js
JavaScript
class None { stub() {} }
willcrichton/ilc-swc
1
Rust
willcrichton
Will Crichton
Brown University