UNPKG

2.14 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = void 0;
7
8var _helperPluginUtils = require("@babel/helper-plugin-utils");
9
10var _pluginSyntaxFunctionBind = require("@babel/plugin-syntax-function-bind");
11
12var _core = require("@babel/core");
13
14var _default = (0, _helperPluginUtils.declare)(api => {
15 api.assertVersion(7);
16
17 function getTempId(scope) {
18 let id = scope.path.getData("functionBind");
19 if (id) return _core.types.cloneNode(id);
20 id = scope.generateDeclaredUidIdentifier("context");
21 return scope.path.setData("functionBind", id);
22 }
23
24 function getStaticContext(bind, scope) {
25 const object = bind.object || bind.callee.object;
26 return scope.isStatic(object) && (_core.types.isSuper(object) ? _core.types.thisExpression() : object);
27 }
28
29 function inferBindContext(bind, scope) {
30 const staticContext = getStaticContext(bind, scope);
31 if (staticContext) return _core.types.cloneNode(staticContext);
32 const tempId = getTempId(scope);
33
34 if (bind.object) {
35 bind.callee = _core.types.sequenceExpression([_core.types.assignmentExpression("=", tempId, bind.object), bind.callee]);
36 } else {
37 bind.callee.object = _core.types.assignmentExpression("=", tempId, bind.callee.object);
38 }
39
40 return _core.types.cloneNode(tempId);
41 }
42
43 return {
44 name: "proposal-function-bind",
45 inherits: _pluginSyntaxFunctionBind.default,
46 visitor: {
47 CallExpression({
48 node,
49 scope
50 }) {
51 const bind = node.callee;
52 if (!_core.types.isBindExpression(bind)) return;
53 const context = inferBindContext(bind, scope);
54 node.callee = _core.types.memberExpression(bind.callee, _core.types.identifier("call"));
55 node.arguments.unshift(context);
56 },
57
58 BindExpression(path) {
59 const {
60 node,
61 scope
62 } = path;
63 const context = inferBindContext(node, scope);
64 path.replaceWith(_core.types.callExpression(_core.types.memberExpression(node.callee, _core.types.identifier("bind")), [context]));
65 }
66
67 }
68 };
69});
70
71exports.default = _default;
\No newline at end of file