Skip to content

[BUG] $$escape does not transform code as expected #86

@unclesmiley

Description

@unclesmiley

Describe the bug

I'm using ts-macros to transform synchronous functions into asynchronous functions. However, the $$escape macro is not working as expected. Instead of directly modifying the function to be escaped, it is wrapping the function in an IIFE, which is not the desired output.

Code to reproduce

import * as ts from "typescript"
import { $$escape, $$raw, RawContext } from "ts-macros"

function $asyncify(fn: Function) {
  return $$escape!(() => {
    return $$raw!((ctx: RawContext, fnAst: ts.FunctionDeclaration) => {

      if (ctx.ts.isFunctionDeclaration(fnAst) || ctx.ts.isArrowFunction(fnAst) || ctx.ts.isFunctionExpression(fnAst)) {
          let asyncFnAst = ctx.factory.updateFunctionDeclaration(
              fnAst,
              [ctx.factory.createModifier(ctx.ts.SyntaxKind.AsyncKeyword)],
              fnAst.asteriskToken,
              fnAst.name,
              fnAst.typeParameters,
              fnAst.parameters,
              fnAst.type,
              fnAst.body
          );

          return asyncFnAst;
      }
    })
  })
}

$asyncify!(function foo() {
  return console.log(1);
})

const foo2 = $asyncify!(() => {
  return console.log(2);
})

const foo3 = $asyncify!(function () {
  return console.log(3);
})

The current output is:

(() => {
    async function foo() {
        return console.log(1);
    }
})();

const foo2 = (() => {
    async function () {
        return console.log(2);
    }
})();

const foo3 = (() => {
    async function () {
        return console.log(3);
    }
})();

Expected behavior

However, my expected output is:

async function foo() {
  return console.log(1);
}
const foo2 = async () => {
  return console.log(2);
};
const foo3 = async function () {
  return console.log(3);
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions