hoist.js 5.8 KB

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