facebook/regenerator

Shouldn't optimize if(false) to if(true) ... break

meyer9 opened this issue · 1 comments

regenerator shouldn't change code of the form:

if (false) {
  // do something
}

to

case 1:
  if (true) break;
  // do something

It seems to be a little more complex than just moving the return statement outside of the if statement. Even this code causes an error:

async function test() {
  if (false) {
    console.log('do something')
    return {}
  } else {
    return {t: 1}
  }
}

Generates this:

"use strict";

function test() {
  return regeneratorRuntime.async(function test$(_context) {
    while (1) switch (_context.prev = _context.next) {
      case 0:
        if (!false) {
          _context.next = 5;
          break;
        }

        console.log('do something');
        return _context.abrupt("return", {});

      case 5:
        return _context.abrupt("return", {
          t: 1
        });

      case 6:
      case "end":
        return _context.stop();
    }
  });
}

The problem is that this prevents optimizing out the if (false) require on the client-side (the require should only run on the server).

Related: vercel/next.js#9298

Basic test:

const code = `
async function test() {
  if (false) {
    console.log('do something')
    return {}
  } else {
    return {t: 1}
  }
}
`

const compiled = require("@babel/core").transformSync(code, {
  configFile: false,
  plugins: [
    require("regenerator-transform"),
    require("@babel/plugin-transform-modules-commonjs")
  ]
}).code;

console.log(compiled)
console.assert(compiled.indexOf('if (!false)') === -1)