Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Babel.js transform generator into non-sequential switch case?

I happens to view code generated by babel.js. The original source code is like this:

function * foo() {
  yield 1;
  yield 2;
  yield 3;
}

The generated ES5 code is like:

"use strict";

var _marked = [foo].map(regeneratorRuntime.mark);

function foo() {
  return regeneratorRuntime.wrap(function foo$(_context) {
    while (1) {
      switch (_context.prev = _context.next) {
        case 0:
          _context.next = 2;
          return 1;

        case 2:
          _context.next = 4;
          return 2;

        case 4:
          _context.next = 6;
          return 3;

        case 6:
        case "end":
          return _context.stop();
      }
    }
  }, _marked[0], this);
}

My question is: why the generated case value is 0, 2, 4 and 6 instead of 0, 1, 2, 3?

Is there any reasoning behind this design?

like image 758
Morgan Cheng Avatar asked Jul 25 '26 08:07

Morgan Cheng


1 Answers

why the generated case value is 0, 2, 4 and 6 instead of 0, 1, 2, 3?

The case values don't really matter, they're not serially numbered because some of them were omitted. The code is generated here, where cases are only inserted in the listing when they are marked. What that means is even commented:

// A sparse array whose keys correspond to locations in this.listing
// that have been marked as branch/jump targets.
this.marked = [true];

The listing is just a list of statements - in fact very much the statements you're seeing in the output. For the particular code in your question, every time a yield expression is encountered, it does emit an assignment to context.next and the actual return statement with the yielded value, and marks the next statement as a jump target. This is where your numbers are coming from. If you add some lines, they'll change.

like image 75
Bergi Avatar answered Jul 28 '26 08:07

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!