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

Statements: 96.31% (209 / 217)      Branches: 90.98% (111 / 122)      Functions: 100% (32 / 32)      Lines: 96.97% (192 / 198)      Ignored: none     

All files » 6to5/transformation/transformers/ » es6-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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 4751 1 1 1   1 1661 853 788   125 125 125     1 149     1 605 26       1 601     1 75 75 13 13     75   7     75 75   75   4       1 604 534 534                           1 609 609 609 609 609   609 609             1 609   609 605   605     605     605     230       43     43       11     11     11     11     11 11     11     11     11 11   11 11         11               1 594               1 605 605   605   9 143 53 32 29     9 6 6     9 9 2 2 2     9                 1 605 605 605   605                                   605 79   79     9       605 13   13 13 13   13 13     605 978   59 63 63       605                       1 11           11   11 149   149 11     138 138 2 2 136 3 3       138 3 3         138     11               1 11 11 149       149       149 1 148 11                         1 11 11 11 6   11               1 43 43       43 471 11   40     15       15   14     14     6     11 460 4       43                     1 1 1     1   1 1   1 1     1                   1 11 11 6   5                     1 6   6       6 6 6 6   6   3         6     4   4 2     4 3     4 1     4 3 3         1     2      
var traverse = require("../../traverse");
var util     = require("../../util");
var t        = require("../../types");
var _        = require("lodash");
 
var isLet = function (node) {
  if (!t.isVariableDeclaration(node)) return false;
  if (node._let) return true;
  if (node.kind !== "let") return false;
 
  node._let = true;
  node.kind = "var";
  return true;
};
 
var isVar = function (node) {
  return t.isVariableDeclaration(node, { kind: "var" }) && !isLet(node);
};
 
var standardiseLets = function (declars) {
  _.each(declars, function (declar) {
    delete declar._let;
  });
};
 
exports.VariableDeclaration = function (node) {
  isLet(node);
};
 
exports.For = function (node, parent, file, scope) {
  var init = node.left || node.init;
  if (isLet(init)) {
    t.ensureBlock(node);
    node.body._letDeclars = [init];
  }
 
  if (t.isLabeledStatement(parent)) {
    // set label so `run` has access to it
    node.label = parent.label;
  }
 
  var letScoping = new LetScoping(node, node.body, parent, file, scope);
  letScoping.run();
 
  if (node.label && !t.isLabeledStatement(parent)) {
    // we've been given a label so let's wrap ourselves
    return t.labeledStatement(node.label, node);
  }
};
 
exports.BlockStatement = function (block, parent, file, scope) {
  if (!t.isFor(parent)) {
    var letScoping = new LetScoping(false, block, parent, file, scope);
    letScoping.run();
  }
};
 
/**
 * Description
 *
 * @param {Boolean|Node} forParent
 * @param {Node} block
 * @param {Node} parent
 * @param {File} file
 * @param {Scope} scope
 */
 
function LetScoping(forParent, block, parent, file, scope) {
  this.forParent = forParent;
  this.parent    = parent;
  this.scope     = scope;
  this.block     = block;
  this.file      = file;
 
  this.letReferences = {};
  this.body          = [];
}
 
/**
 * Start the ball rolling.
 */
 
LetScoping.prototype.run = function () {
  var block = this.block;
 
  if (block._letDone) return;
  block._letDone = true;
 
  this.info = this.getInfo();
 
  // remap all let references that exist in upper scopes to their uid
  this.remap();
 
  // this is a block within a `Function` so we can safely leave it be
  if (t.isFunction(this.parent)) return this.noClosure();
 
  // this block has no let references so let's clean up
  if (!this.info.keys.length) return this.noClosure();
 
  // returns whether or not there are any outside let references within any
  // functions
  var referencesInClosure = this.getLetReferences();
 
  // no need for a closure so let's clean up
  if (!referencesInClosure) return this.noClosure();
 
  // if we're inside of a for loop then we search to see if there are any
  // `break`s, `continue`s, `return`s etc
  this.has = this.checkFor();
 
  // hoist var references to retain scope
  this.hoistVarDeclarations();
 
  // set let references to plain var references
  standardiseLets(this.info.declarators);
 
  // turn letReferences into an array
  var letReferences = _.values(this.letReferences);
 
  // build the closure that we're going to wrap the block with
  var fn = t.functionExpression(null, letReferences, t.blockStatement(block.body));
  fn._aliasFunction = true;
 
  // replace the current block body with the one we're going to build
  block.body = this.body;
 
  // change upper scope references with their uid if they have one
  var params = this.getParams(letReferences);
 
  // build a call and a unique id that we can assign the return value to
  var call = t.callExpression(fn, params);
  var ret  = this.file.generateUidIdentifier("ret", this.scope);
 
  var hasYield = traverse.hasType(fn.body, "YieldExpression", t.FUNCTION_TYPES);
  Iif (hasYield) {
    fn.generator = true;
    call = t.yieldExpression(call, true);
  }
 
  this.build(ret, call);
};
 
/**
 * There are no let references accessed within a closure so we can just turn the
 * lets into vars.
 */
 
LetScoping.prototype.noClosure = function () {
  standardiseLets(this.info.declarators);
};
 
/**
 * Traverse through block and replace all references that exist in a higher
 * scope to their uids.
 */
 
LetScoping.prototype.remap = function () {
  var replacements = this.info.duplicates;
  var block        = this.block;
 
  if (_.isEmpty(replacements)) return;
 
  var replace = function (node, parent, scope) {
    if (!t.isIdentifier(node)) return;
    if (!t.isReferenced(node, parent)) return;
    if (scope && scope.hasOwn(node.name)) return;
    node.name = replacements[node.name] || node.name;
  };
 
  var traverseReplace = function (node, parent) {
    replace(node, parent);
    traverse(node, replace);
  };
 
  var forParent = this.forParent;
  if (forParent) {
    traverseReplace(forParent.right, forParent);
    traverseReplace(forParent.test, forParent);
    traverseReplace(forParent.update, forParent);
  }
 
  traverse(block, replace);
};
 
/**
 * Description
 *
 * @returns {Object}
 */
 
LetScoping.prototype.getInfo = function () {
  var block = this.block;
  var scope = this.scope;
  var file  = this.file;
 
  var opts = {
    // array of `Identifier` names of let variables that appear lexically out of
    // this scope but should be accessible - eg. `ForOfStatement`.left
    outsideKeys: [],
 
    // array of let `VariableDeclarator`s that are a part of this block
    declarators: block._letDeclars || [],
 
    // object of duplicate ids and their aliases - if there's an `Identifier`
    // name that's used in an upper scope we generate a unique id and replace
    // all references with it
    duplicates:  {},
 
    // array of `Identifier` names of let variables that are accessible within
    // the current block
    keys:        []
  };
 
  var duplicates = function (id, key) {
    var has = scope.parentGet(key);
 
    if (has && has !== id) {
      // there's a variable with this exact name in an upper scope so we need
      // to generate a new name
      opts.duplicates[key] = id.name = file.generateUid(key, scope);
    }
  };
 
  _.each(opts.declarators, function (declar) {
    opts.declarators.push(declar);
 
    var keys = t.getIds(declar, true);
    _.each(keys, duplicates);
    keys = _.keys(keys);
 
    opts.outsideKeys = opts.outsideKeys.concat(keys);
    opts.keys = opts.keys.concat(keys);
  });
 
  _.each(block.body, function (declar) {
    if (!isLet(declar)) return;
 
    _.each(t.getIds(declar, true), function (id, key) {
      duplicates(id, key);
      opts.keys.push(key);
    });
  });
 
  return opts;
};
 
/**
 * If we're inside of a `For*Statement` then traverse it and check if it has one
 * of the following node types `ReturnStatement`, `BreakStatement`,
 * `ContinueStatement` and replace it with a return value that we can track
 * later on.
 *
 * @returns {Object}
 */
 
LetScoping.prototype.checkFor = function () {
  var has = {
    hasContinue: false,
    hasReturn:   false,
    hasBreak:    false,
  };
 
  var forParent = this.forParent;
 
  traverse(this.block, function (node) {
    var replace;
 
    if (t.isFunction(node) || t.isFor(node)) {
      return false;
    }
 
    Eif (forParent && node && !node.label) {
      if (t.isBreakStatement(node)) {
        has.hasBreak = true;
        replace = t.returnStatement(t.literal("break"));
      } else if (t.isContinueStatement(node)) {
        has.hasContinue = true;
        replace = t.returnStatement(t.literal("continue"));
      }
    }
 
    if (t.isReturnStatement(node)) {
      has.hasReturn = true;
      replace = t.returnStatement(t.objectExpression([
        t.property("init", t.identifier("v"), node.argument || t.identifier("undefined"))
      ]));
    }
 
    if (replace) return t.inherits(replace, node);
  });
 
  return has;
};
 
/**
 * Hoist all var declarations in this block to before it so they retain scope
 * once we wrap everything in a closure.
 */
 
LetScoping.prototype.hoistVarDeclarations = function () {
  var self = this;
  traverse(this.block, function (node) {
    Iif (t.isForStatement(node)) {
      if (isVar(node.init)) {
        node.init = t.sequenceExpression(self.pushDeclar(node.init));
      }
    } else Iif (t.isFor(node)) {
      if (isVar(node.left)) {
        node.left = node.left.declarations[0].id;
      }
    } else if (isVar(node)) {
      return self.pushDeclar(node).map(t.expressionStatement);
    } else if (t.isFunction(node)) {
      return false;
    }
  });
};
 
/**
 * Build up a parameter list that we'll call our closure wrapper with, replacing
 * all duplicate ids with their uid.
 *
 * @param {Array} params
 * @returns {Array}
 */
 
LetScoping.prototype.getParams = function (params) {
  var info = this.info;
  params = _.cloneDeep(params);
  _.each(params, function (param) {
    param.name = info.duplicates[param.name] || param.name;
  });
  return params;
};
 
/**
 * Get all let references within this block. Stopping whenever we reach another
 * block.
 */
 
LetScoping.prototype.getLetReferences = function () {
  var closurify = false;
  var self = this;
 
  // traverse through this block, stopping on functions and checking if they
  // contain any outside let references
  traverse(this.block, function (node, parent, scope) {
    if (t.isFunction(node)) {
      traverse(node, function (node, parent) {
        // not an identifier so we have no use
        if (!t.isIdentifier(node)) return;
 
        // not a direct reference
        Iif (!t.isReferenced(node, parent)) return;
 
        // this scope has a variable with the same name so it couldn't belong
        // to our let scope
        if (scope.hasOwn(node.name)) return;
 
        closurify = true;
 
        // this key doesn't appear just outside our scope
        if (!_.contains(self.info.outsideKeys, node.name)) return;
 
        // push this badboy
        self.letReferences[node.name] = node;
      });
 
      return false;
    } else if (t.isFor(node)) {
      return false;
    }
  });
 
  return closurify;
};
 
/**
 * Turn a `VariableDeclaration` into an array of `AssignmentExpressions` with
 * their declarations hoisted to before the closure wrapper.
 *
 * @param {Node} node VariableDeclaration
 * @returns {Array}
 */
 
LetScoping.prototype.pushDeclar = function (node) {
  this.body.push(t.variableDeclaration(node.kind, node.declarations.map(function (declar) {
    return t.variableDeclarator(declar.id);
  })));
 
  var replace = [];
 
  _.each(node.declarations, function (declar) {
    Iif (!declar.init) return;
 
    var expr = t.assignmentExpression("=", declar.id, declar.init);
    replace.push(t.inherits(expr, declar));
  });
 
  return replace;
};
 
/**
 * Push the closure to the body.
 *
 * @param {Node} ret Identifier
 * @param {Node} call CallExpression
 */
 
LetScoping.prototype.build = function (ret, call) {
  var has = this.has;
  if (has.hasReturn || has.hasBreak || has.hasContinue) {
    this.buildHas(ret, call);
  } else {
    this.body.push(t.expressionStatement(call));
  }
};
 
/**
 * Description
 *
 * @param {Node} ret Identifier
 * @param {Node} call CallExpression
 */
 
LetScoping.prototype.buildHas = function (ret, call) {
  var body = this.body;
 
  body.push(t.variableDeclaration("var", [
    t.variableDeclarator(ret, call)
  ]));
 
  var forParent = this.forParent;
  var retCheck;
  var has = this.has;
  var cases = [];
 
  if (has.hasReturn) {
    // typeof ret === "object"
    retCheck = util.template("let-scoping-return", {
      RETURN: ret
    });
  }
 
  if (has.hasBreak || has.hasContinue) {
    // ensure that the parent has a label as we're building a switch and we
    // need to be able to access it
    var label = forParent.label = forParent.label || this.file.generateUidIdentifier("loop", this.scope);
 
    if (has.hasBreak) {
      cases.push(t.switchCase(t.literal("break"), [t.breakStatement(label)]));
    }
 
    if (has.hasContinue) {
      cases.push(t.switchCase(t.literal("continue"), [t.continueStatement(label)]));
    }
 
    if (has.hasReturn) {
      cases.push(t.switchCase(null, [retCheck]));
    }
 
    if (cases.length === 1) {
      var single = cases[0];
      body.push(t.ifStatement(
        t.binaryExpression("===", ret, single.test),
        single.consequent[0]
      ));
    } else {
      body.push(t.switchStatement(ret, cases));
    }
  } else {
    Eif (has.hasReturn) body.push(retCheck);
  }
};