facebookarchive/prepack

Optimizing the body of "for of" loop that has been compiled with Babel

trueadm opened this issue · 0 comments

Take the case:

function fn(attachment) {
  for (
    var _iterator = attachment.style_list,
      _isArray = Array.isArray(_iterator),
      _i = 0,
      _iterator = _isArray
        ? _iterator
        : _iterator[
            typeof Symbol === "function"
              ? typeof Symbol === "function"
                ? Symbol.iterator
                : "@@iterator"
              : "@@iterator"
          ]();
    ;

  ) {
    var _ref;
    if (_isArray) {
      if (_i >= _iterator.length) break;
      _ref = _iterator[_i++];
    } else {
      _i = _iterator.next();
      if (_i.done) break;
      _ref = _i.value;
    }
    var style = _ref;
    switch (style) {
      case "A":
        return null;
      case "B":
        return React.createElement(SomeComponent, { ... });
      case "C":
        return React.createElement(SomeComponent, { ... });
      case "D":
        return React.createElement(SomeComponent, { ... });
      case "E":
        return React.createElement(SomeComponent, { ... });
      case "F":
        return React.createElement(SomeComponent, { ... });
      case "G":
        return React.createElement(SomeComponent, { ... });
      case "H":
      case "I":
      case "J":
        return React.createElement(SomeComponent, { ... });
    }
  }
  return React.createElement(SomeComponent, { ... });
}

__optimize(fn);

Above, this will fail currently and not bail out because we don't support return in loop bodies. We can add support for this but it won't gain us too much by itself. What we really want to do be able to do is bail-out, then optimize the nested function generated. Somehow, we need to extract the "for" part so we can do this though (otherwise it will recursively keep generating a bailout loop).

@hermanventer @sebmarkbage any thoughts on how we might handle this pattern? Might it be that we actually should preference the original ES2015 code in this case until we can support these difficult problems in Prepack?