index.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = _default;
  6. function _helperHoistVariables() {
  7. const data = _interopRequireDefault(require("@babel/helper-hoist-variables"));
  8. _helperHoistVariables = function () {
  9. return data;
  10. };
  11. return data;
  12. }
  13. function t() {
  14. const data = _interopRequireWildcard(require("@babel/types"));
  15. t = function () {
  16. return data;
  17. };
  18. return data;
  19. }
  20. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
  21. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  22. const visitor = {
  23. enter(path, state) {
  24. if (path.isThisExpression()) {
  25. state.foundThis = true;
  26. }
  27. if (path.isReferencedIdentifier({
  28. name: "arguments"
  29. })) {
  30. state.foundArguments = true;
  31. }
  32. },
  33. Function(path) {
  34. path.skip();
  35. }
  36. };
  37. function _default(path, scope = path.scope) {
  38. const {
  39. node
  40. } = path;
  41. const container = t().functionExpression(null, [], node.body, node.generator, node.async);
  42. let callee = container;
  43. let args = [];
  44. (0, _helperHoistVariables().default)(path, id => scope.push({
  45. id
  46. }));
  47. const state = {
  48. foundThis: false,
  49. foundArguments: false
  50. };
  51. path.traverse(visitor, state);
  52. if (state.foundArguments || state.foundThis) {
  53. callee = t().memberExpression(container, t().identifier("apply"));
  54. args = [];
  55. if (state.foundThis) {
  56. args.push(t().thisExpression());
  57. }
  58. if (state.foundArguments) {
  59. if (!state.foundThis) args.push(t().nullLiteral());
  60. args.push(t().identifier("arguments"));
  61. }
  62. }
  63. let call = t().callExpression(callee, args);
  64. if (node.generator) call = t().yieldExpression(call, true);
  65. return t().returnStatement(call);
  66. }