Skip to content
This repository has been archived by the owner on Feb 1, 2025. It is now read-only.

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

Open
meyer9 opened this issue Nov 4, 2019 · 1 comment
Open

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

meyer9 opened this issue Nov 4, 2019 · 1 comment

Comments

@meyer9
Copy link

meyer9 commented Nov 4, 2019

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

@meyer9
Copy link
Author

meyer9 commented Nov 4, 2019

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)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant