You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
2.4 KiB

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