hoist.js 4.7 KB

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