hoist.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. "use strict";
  2. var util = _interopRequireWildcard(require("./util"));
  3. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  4. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  5. /**
  6. * Copyright (c) 2014-present, Facebook, Inc.
  7. *
  8. * This source code is licensed under the MIT license found in the
  9. * LICENSE file in the root directory of this source tree.
  10. */
  11. var hasOwn = Object.prototype.hasOwnProperty; // The hoist function takes a FunctionExpression or FunctionDeclaration
  12. // and replaces any Declaration nodes in its body with assignments, then
  13. // returns a VariableDeclaration containing just the names of the removed
  14. // declarations.
  15. exports.hoist = function (funPath) {
  16. var t = util.getTypes();
  17. t.assertFunction(funPath.node);
  18. var vars = {};
  19. function varDeclToExpr(_ref, includeIdentifiers) {
  20. var vdec = _ref.node,
  21. scope = _ref.scope;
  22. t.assertVariableDeclaration(vdec); // TODO assert.equal(vdec.kind, "var");
  23. var exprs = [];
  24. vdec.declarations.forEach(function (dec) {
  25. // Note: We duplicate 'dec.id' here to ensure that the variable declaration IDs don't
  26. // have the same 'loc' value, since that can make sourcemaps and retainLines behave poorly.
  27. vars[dec.id.name] = t.identifier(dec.id.name); // Remove the binding, to avoid "duplicate declaration" errors when it will
  28. // be injected again.
  29. scope.removeBinding(dec.id.name);
  30. if (dec.init) {
  31. exprs.push(t.assignmentExpression("=", dec.id, dec.init));
  32. } else if (includeIdentifiers) {
  33. exprs.push(dec.id);
  34. }
  35. });
  36. if (exprs.length === 0) return null;
  37. if (exprs.length === 1) return exprs[0];
  38. return t.sequenceExpression(exprs);
  39. }
  40. funPath.get("body").traverse({
  41. VariableDeclaration: {
  42. exit: function exit(path) {
  43. var expr = varDeclToExpr(path, false);
  44. if (expr === null) {
  45. path.remove();
  46. } else {
  47. // We don't need to traverse this expression any further because
  48. // there can't be any new declarations inside an expression.
  49. util.replaceWithOrRemove(path, t.expressionStatement(expr));
  50. } // Since the original node has been either removed or replaced,
  51. // avoid traversing it any further.
  52. path.skip();
  53. }
  54. },
  55. ForStatement: function ForStatement(path) {
  56. var init = path.get("init");
  57. if (init.isVariableDeclaration()) {
  58. util.replaceWithOrRemove(init, varDeclToExpr(init, false));
  59. }
  60. },
  61. ForXStatement: function ForXStatement(path) {
  62. var left = path.get("left");
  63. if (left.isVariableDeclaration()) {
  64. util.replaceWithOrRemove(left, varDeclToExpr(left, true));
  65. }
  66. },
  67. FunctionDeclaration: function FunctionDeclaration(path) {
  68. var node = path.node;
  69. vars[node.id.name] = node.id;
  70. var assignment = t.expressionStatement(t.assignmentExpression("=", t.clone(node.id), t.functionExpression(path.scope.generateUidIdentifierBasedOnNode(node), node.params, node.body, node.generator, node.expression)));
  71. if (path.parentPath.isBlockStatement()) {
  72. // Insert the assignment form before the first statement in the
  73. // enclosing block.
  74. path.parentPath.unshiftContainer("body", assignment); // Remove the function declaration now that we've inserted the
  75. // equivalent assignment form at the beginning of the block.
  76. path.remove();
  77. } else {
  78. // If the parent node is not a block statement, then we can just
  79. // replace the declaration with the equivalent assignment form
  80. // without worrying about hoisting it.
  81. util.replaceWithOrRemove(path, assignment);
  82. } // Remove the binding, to avoid "duplicate declaration" errors when it will
  83. // be injected again.
  84. path.scope.removeBinding(node.id.name); // Don't hoist variables out of inner functions.
  85. path.skip();
  86. },
  87. FunctionExpression: function FunctionExpression(path) {
  88. // Don't descend into nested function expressions.
  89. path.skip();
  90. },
  91. ArrowFunctionExpression: function ArrowFunctionExpression(path) {
  92. // Don't descend into nested function expressions.
  93. path.skip();
  94. }
  95. });
  96. var paramNames = {};
  97. funPath.get("params").forEach(function (paramPath) {
  98. var param = paramPath.node;
  99. if (t.isIdentifier(param)) {
  100. paramNames[param.name] = param;
  101. } else {// Variables declared by destructuring parameter patterns will be
  102. // harmlessly re-declared.
  103. }
  104. });
  105. var declarations = [];
  106. Object.keys(vars).forEach(function (name) {
  107. if (!hasOwn.call(paramNames, name)) {
  108. declarations.push(t.variableDeclarator(vars[name], null));
  109. }
  110. });
  111. if (declarations.length === 0) {
  112. return null; // Be sure to handle this case!
  113. }
  114. return t.variableDeclaration("var", declarations);
  115. };