Code coverage report for 6to5/transformers/let-scoping.js

Statements: 100% (38 / 38)      Branches: 100% (20 / 20)      Functions: 100% (6 / 6)      Lines: 100% (33 / 33)      Ignored: none     

All files » 6to5/transformers/ » let-scoping.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 611 1 1 1   1 294 59   59   59 64 68       59   1762     651 651   147     59   59 1709 14   14 67 67 67     14 6 1   5     5 5     8       1695     59    
var traverse = require("../traverse");
var util     = require("../util");
var b        = require("acorn-ast-types").builders;
var _        = require("lodash");
 
exports.VariableDeclaration = function (node, parent, file) {
  if (node.kind !== "let") return;
  node.kind = "var";
 
  var ids = {};
 
  _.each(node.declarations, function (declar) {
    _.each(util.getIds(declar.id), function (id) {
      ids[id] = b.identifier(file.generateUid(id));
    });
  });
 
  var replaceId = function (node, parent) {
    // not an identifier so we have no use for this node
    if (node.type !== "Identifier") return;
 
    // not a let reference
    var id = ids[node.name];
    if (!id) return;
 
    if (util.isReferenced(node, parent)) return id;
  };
 
  var isProgram = parent.type === "Program";
 
  var replace = function (node, parent) {
    if (!isProgram && _.contains(traverse.FUNCTION_TYPES, node.type)) {
      var letReferences = [];
 
      traverse(node, function (node, parent) {
        var id = replaceId(node, parent);
        if (id && !_.contains(letReferences, id)) letReferences.push(id);
        return id;
      });
 
      if (letReferences.length) {
        if (node.type === "FunctionDeclaration") {
          throw new Error("`FunctionDeclaration`s that use `let` and `constant` references aren't allowed outside of the root scope");
        } else {
          var func = b.functionExpression(null, letReferences, b.blockStatement([
            b.returnStatement(node)
          ]));
          func._aliasFunction = true;
          return b.callExpression(func, letReferences);
        }
      } else {
        return false;
      }
    }
 
    return replaceId(node, parent);
  };
 
  traverse(parent, replace);
};