UNPKG

2.45 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = _default;
7
8var _helperHoistVariables = _interopRequireDefault(require("@babel/helper-hoist-variables"));
9
10var t = _interopRequireWildcard(require("@babel/types"));
11
12function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
13
14function _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; }
15
16function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17
18const visitor = {
19 enter(path, state) {
20 if (path.isThisExpression()) {
21 state.foundThis = true;
22 }
23
24 if (path.isReferencedIdentifier({
25 name: "arguments"
26 })) {
27 state.foundArguments = true;
28 }
29 },
30
31 Function(path) {
32 path.skip();
33 }
34
35};
36
37function _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
53 if (state.foundArguments || state.foundThis) {
54 callee = t.memberExpression(container, t.identifier("apply"));
55 args = [];
56
57 if (state.foundThis) {
58 args.push(t.thisExpression());
59 }
60
61 if (state.foundArguments) {
62 if (!state.foundThis) args.push(t.nullLiteral());
63 args.push(t.identifier("arguments"));
64 }
65 }
66
67 let call = t.callExpression(callee, args);
68 if (node.generator) call = t.yieldExpression(call, true);
69 return t.returnStatement(call);
70}
\No newline at end of file