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

Statements: 84.85% (140 / 165)      Branches: 78.76% (89 / 113)      Functions: 88% (22 / 25)      Lines: 85.14% (126 / 148)      Ignored: none     

All files » 6to5/transformation/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 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 3171 1 1   1 788 504 458   69 69 69     1 55     1 356     1 44 44 7 7     44   3     44   44   1       1 267 224       1 61   61   2 32 13 10       1 65 14       1 267                                   267 7   7 7 7     267 384   42 46   46     2     46       267     1 4           4 4 55   55 4 51     51 1 1 50             51       4     1 4 55       55       55   55 4         1 29       29 284 4   17     7       7   7     7     1     4 280 4       29     1 268 267   267 267 267     267     65     29       29   29     29       4   4     4                                   4     4     4 4     4     4 4 1     4 4   4 1       1   1                         1     1   1   1       1 1     1       1     3      
var traverse = require("../../traverse");
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);
};
 
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;
  }
 
  run(node, node.body, parent, file, scope);
 
  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)) {
    run(false, block, parent, file, scope);
  }
};
 
var noClosure = function (letDeclars, block, replacements) {
  standardiseLets(letDeclars);
 
  if (_.isEmpty(replacements)) return;
 
  traverse(block, function (node, parent) {
    if (!t.isIdentifier(node)) return;
    if (!t.isReferenced(node, parent)) return;
    node.name = replacements[node.name] || node.name;
  });
};
 
var standardiseLets = function (declars) {
  _.each(declars, function (declar) {
    delete declar._let;
  });
};
 
var getInfo = function (block, file, scope) {
  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:        []
  };
 
  _.each(opts.declarators, function (declar) {
    opts.declarators.push(declar);
 
    var keys = t.getIds(declar);
    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) {
      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);
      }
 
      opts.keys.push(key);
    });
  });
 
  return opts;
};
 
var checkFor = function (forParent, block) {
  var has = {
    hasContinue: false,
    hasReturn:   false,
    hasBreak:    false,
  };
 
  Eif (forParent) {
    traverse(block, function (node) {
      var replace;
 
      if (t.isFunction(node) || t.isFor(node)) {
        return false;
      } else Iif (t.isBreakStatement(node) && !node.label) {
        has.hasBreak = true;
        replace = t.returnStatement(t.literal("break"));
      } else if (t.isContinueStatement(node) && !node.label) {
        has.hasContinue = true;
        replace = t.returnStatement(t.literal("continue"));
      } else Iif (t.isReturnStatement(node)) {
        has.hasReturn = true;
        replace = t.returnStatement(t.objectExpression([
          t.property("init", t.identifier("v"), node.argument)
        ]));
      }
 
      if (replace) return t.inherits(replace, node);
    });
  }
 
  return has;
};
 
var hoistVarDeclarations = function (block, pushDeclar) {
  traverse(block, function (node) {
    Iif (t.isForStatement(node)) {
      if (isVar(node.init)) {
        node.init = t.sequenceExpression(pushDeclar(node.init));
      }
    } else Iif (t.isFor(node)) {
      if (isVar(node.left)) {
        node.left = node.left.declarations[0].id;
      }
    } else Iif (isVar(node)) {
      return pushDeclar(node).map(t.expressionStatement);
    } else if (t.isFunction(node)) {
      return false;
    }
  });
};
 
var getLetReferences = function (info, block, letReferences) {
  var closurify = false;
 
  // traverse through this block, stopping on functions and checking if they
  // contain any outside let references
  traverse(block, function (node, parent, opts) {
    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
        Iif (opts.scope.hasOwn(node.name)) return;
 
        closurify = true;
 
        // this key doesn't appear just outside our scope
        if (!_.contains(info.outsideKeys, node.name)) return;
 
        // push this badboy
        letReferences[node.name] = node;
      });
 
      return false;
    } else if (t.isFor(node)) {
      return false;
    }
  });
 
  return closurify;
};
 
var run = function (forParent, block, parent, file, scope) {
  if (block._letDone) return;
  block._letDone = true;
 
  var info = getInfo(block, file, scope);
  var declarators = info.declarators;
  var letKeys = info.keys;
 
  // this is a block within a `Function` so we can safely leave it be
  if (t.isFunction(parent)) return;
 
  // this block has no let references so let's clean up
  if (!letKeys.length) return noClosure(declarators, block, info.duplicates);
 
  // outside let references that we need to wrap
  var letReferences = {};
 
  // returns whether or not there are any outside let references within any
  // functions
  var closurify = getLetReferences(info, block, letReferences);
 
  letReferences = _.values(letReferences);
 
  // no need for a closure so let's clean up
  if (!closurify) return noClosure(declarators, block, info.duplicates);
 
  // if we're inside of a for loop then we search to see if there are any
  // `break`s, `continue`s, `return`s etc
  var has = checkFor(forParent, block);
 
  var body = [];
 
  // hoist a `VariableDeclaration` and add `AssignmentExpression`s in it's place
  var pushDeclar = function (node) {
    body.push(t.variableDeclaration(node.kind, node.declarations.map(function (declar) {
      return t.variableDeclarator(declar.id);
    })));
 
    var replace = [];
 
    _.each(node.declarations, function (declar) {
      if (!declar.init) return;
 
      var expr = t.assignmentExpression("=", declar.id, declar.init);
      replace.push(t.inherits(expr, declar));
    });
 
    return replace;
  };
 
  // hoist var references to retain scope
  hoistVarDeclarations(block, pushDeclar);
 
  // set let references to plain var references
  standardiseLets(declarators);
 
  // 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've built
  block.body = body;
 
  // cahnge duplicate let references to their uid if they have one
  var params = _.cloneDeep(letReferences);
  _.each(params, function (param) {
    param.name = info.duplicates[param.name] || param.name;
  });
 
  var call = t.callExpression(fn, params);
  var ret  = t.identifier(file.generateUid("ret", scope));
 
  if (has.hasReturn || has.hasBreak || has.hasContinue) {
    body.push(t.variableDeclaration("var", [
      t.variableDeclarator(ret, call)
    ]));
 
    var retCheck;
 
    Iif (has.hasReturn) {
      // typeof ret === "object"
      retCheck = t.ifStatement(
        t.binaryExpression("===", t.unaryExpression("typeof", ret, true), t.literal("object")),
        t.returnStatement(t.memberExpression(ret, t.identifier("v")))
      );
 
      // there's no `break` or `continue` so we can just push in the `if`
      if (!has.hasBreak && !has.hasContinue) {
        body.push(retCheck);
      }
    }
 
    Eif (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 || t.identifier(file.generateUid("loop", scope));
 
      var cases = [];
 
      Iif (has.hasBreak) {
        cases.push(t.switchCase(t.literal("break"), [t.breakStatement(label)]));
      }
 
      Eif (has.hasContinue) {
        cases.push(t.switchCase(t.literal("continue"), [t.continueStatement(label)]));
      }
 
      Iif (has.hasReturn) {
        cases.push(t.switchCase(null, [retCheck]));
      }
 
      body.push(t.switchStatement(ret, cases));
    }
  } else {
    body.push(t.expressionStatement(call));
  }
};