conversion.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.toComputedKey = toComputedKey;
  6. exports.ensureBlock = ensureBlock;
  7. exports.arrowFunctionToShadowed = arrowFunctionToShadowed;
  8. exports.unwrapFunctionEnvironment = unwrapFunctionEnvironment;
  9. exports.arrowFunctionToExpression = arrowFunctionToExpression;
  10. var t = _interopRequireWildcard(require("@babel/types"));
  11. var _helperFunctionName = _interopRequireDefault(require("@babel/helper-function-name"));
  12. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  14. 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; }
  15. function toComputedKey() {
  16. let key;
  17. if (this.isMemberExpression()) {
  18. key = this.node.property;
  19. } else if (this.isProperty() || this.isMethod()) {
  20. key = this.node.key;
  21. } else {
  22. throw new ReferenceError("todo");
  23. }
  24. if (!this.node.computed) {
  25. if (t.isIdentifier(key)) key = t.stringLiteral(key.name);
  26. }
  27. return key;
  28. }
  29. function ensureBlock() {
  30. const body = this.get("body");
  31. const bodyNode = body.node;
  32. if (Array.isArray(body)) {
  33. throw new Error("Can't convert array path to a block statement");
  34. }
  35. if (!bodyNode) {
  36. throw new Error("Can't convert node without a body");
  37. }
  38. if (body.isBlockStatement()) {
  39. return bodyNode;
  40. }
  41. const statements = [];
  42. let stringPath = "body";
  43. let key;
  44. let listKey;
  45. if (body.isStatement()) {
  46. listKey = "body";
  47. key = 0;
  48. statements.push(body.node);
  49. } else {
  50. stringPath += ".body.0";
  51. if (this.isFunction()) {
  52. key = "argument";
  53. statements.push(t.returnStatement(body.node));
  54. } else {
  55. key = "expression";
  56. statements.push(t.expressionStatement(body.node));
  57. }
  58. }
  59. this.node.body = t.blockStatement(statements);
  60. const parentPath = this.get(stringPath);
  61. body.setup(parentPath, listKey ? parentPath.node[listKey] : parentPath.node, listKey, key);
  62. return this.node;
  63. }
  64. function arrowFunctionToShadowed() {
  65. if (!this.isArrowFunctionExpression()) return;
  66. this.arrowFunctionToExpression();
  67. }
  68. function unwrapFunctionEnvironment() {
  69. if (!this.isArrowFunctionExpression() && !this.isFunctionExpression() && !this.isFunctionDeclaration()) {
  70. throw this.buildCodeFrameError("Can only unwrap the environment of a function.");
  71. }
  72. hoistFunctionEnvironment(this);
  73. }
  74. function arrowFunctionToExpression({
  75. allowInsertArrow = true,
  76. specCompliant = false,
  77. noNewArrows = !specCompliant
  78. } = {}) {
  79. if (!this.isArrowFunctionExpression()) {
  80. throw this.buildCodeFrameError("Cannot convert non-arrow function to a function expression.");
  81. }
  82. const thisBinding = hoistFunctionEnvironment(this, noNewArrows, allowInsertArrow);
  83. this.ensureBlock();
  84. this.node.type = "FunctionExpression";
  85. if (!noNewArrows) {
  86. const checkBinding = thisBinding ? null : this.parentPath.scope.generateUidIdentifier("arrowCheckId");
  87. if (checkBinding) {
  88. this.parentPath.scope.push({
  89. id: checkBinding,
  90. init: t.objectExpression([])
  91. });
  92. }
  93. this.get("body").unshiftContainer("body", t.expressionStatement(t.callExpression(this.hub.addHelper("newArrowCheck"), [t.thisExpression(), checkBinding ? t.identifier(checkBinding.name) : t.identifier(thisBinding)])));
  94. this.replaceWith(t.callExpression(t.memberExpression((0, _helperFunctionName.default)(this, true) || this.node, t.identifier("bind")), [checkBinding ? t.identifier(checkBinding.name) : t.thisExpression()]));
  95. }
  96. }
  97. function hoistFunctionEnvironment(fnPath, noNewArrows = true, allowInsertArrow = true) {
  98. const thisEnvFn = fnPath.findParent(p => {
  99. return p.isFunction() && !p.isArrowFunctionExpression() || p.isProgram() || p.isClassProperty({
  100. static: false
  101. });
  102. });
  103. const inConstructor = (thisEnvFn == null ? void 0 : thisEnvFn.node.kind) === "constructor";
  104. if (thisEnvFn.isClassProperty()) {
  105. throw fnPath.buildCodeFrameError("Unable to transform arrow inside class property");
  106. }
  107. const {
  108. thisPaths,
  109. argumentsPaths,
  110. newTargetPaths,
  111. superProps,
  112. superCalls
  113. } = getScopeInformation(fnPath);
  114. if (inConstructor && superCalls.length > 0) {
  115. if (!allowInsertArrow) {
  116. throw superCalls[0].buildCodeFrameError("Unable to handle nested super() usage in arrow");
  117. }
  118. const allSuperCalls = [];
  119. thisEnvFn.traverse({
  120. Function(child) {
  121. if (child.isArrowFunctionExpression()) return;
  122. child.skip();
  123. },
  124. ClassProperty(child) {
  125. child.skip();
  126. },
  127. CallExpression(child) {
  128. if (!child.get("callee").isSuper()) return;
  129. allSuperCalls.push(child);
  130. }
  131. });
  132. const superBinding = getSuperBinding(thisEnvFn);
  133. allSuperCalls.forEach(superCall => {
  134. const callee = t.identifier(superBinding);
  135. callee.loc = superCall.node.callee.loc;
  136. superCall.get("callee").replaceWith(callee);
  137. });
  138. }
  139. if (argumentsPaths.length > 0) {
  140. const argumentsBinding = getBinding(thisEnvFn, "arguments", () => t.identifier("arguments"));
  141. argumentsPaths.forEach(argumentsChild => {
  142. const argsRef = t.identifier(argumentsBinding);
  143. argsRef.loc = argumentsChild.node.loc;
  144. argumentsChild.replaceWith(argsRef);
  145. });
  146. }
  147. if (newTargetPaths.length > 0) {
  148. const newTargetBinding = getBinding(thisEnvFn, "newtarget", () => t.metaProperty(t.identifier("new"), t.identifier("target")));
  149. newTargetPaths.forEach(targetChild => {
  150. const targetRef = t.identifier(newTargetBinding);
  151. targetRef.loc = targetChild.node.loc;
  152. targetChild.replaceWith(targetRef);
  153. });
  154. }
  155. if (superProps.length > 0) {
  156. if (!allowInsertArrow) {
  157. throw superProps[0].buildCodeFrameError("Unable to handle nested super.prop usage");
  158. }
  159. const flatSuperProps = superProps.reduce((acc, superProp) => acc.concat(standardizeSuperProperty(superProp)), []);
  160. flatSuperProps.forEach(superProp => {
  161. const key = superProp.node.computed ? "" : superProp.get("property").node.name;
  162. const isAssignment = superProp.parentPath.isAssignmentExpression({
  163. left: superProp.node
  164. });
  165. const isCall = superProp.parentPath.isCallExpression({
  166. callee: superProp.node
  167. });
  168. const superBinding = getSuperPropBinding(thisEnvFn, isAssignment, key);
  169. const args = [];
  170. if (superProp.node.computed) {
  171. args.push(superProp.get("property").node);
  172. }
  173. if (isAssignment) {
  174. const value = superProp.parentPath.node.right;
  175. args.push(value);
  176. }
  177. const call = t.callExpression(t.identifier(superBinding), args);
  178. if (isCall) {
  179. superProp.parentPath.unshiftContainer("arguments", t.thisExpression());
  180. superProp.replaceWith(t.memberExpression(call, t.identifier("call")));
  181. thisPaths.push(superProp.parentPath.get("arguments.0"));
  182. } else if (isAssignment) {
  183. superProp.parentPath.replaceWith(call);
  184. } else {
  185. superProp.replaceWith(call);
  186. }
  187. });
  188. }
  189. let thisBinding;
  190. if (thisPaths.length > 0 || !noNewArrows) {
  191. thisBinding = getThisBinding(thisEnvFn, inConstructor);
  192. if (noNewArrows || inConstructor && hasSuperClass(thisEnvFn)) {
  193. thisPaths.forEach(thisChild => {
  194. const thisRef = thisChild.isJSX() ? t.jsxIdentifier(thisBinding) : t.identifier(thisBinding);
  195. thisRef.loc = thisChild.node.loc;
  196. thisChild.replaceWith(thisRef);
  197. });
  198. if (!noNewArrows) thisBinding = null;
  199. }
  200. }
  201. return thisBinding;
  202. }
  203. function standardizeSuperProperty(superProp) {
  204. if (superProp.parentPath.isAssignmentExpression() && superProp.parentPath.node.operator !== "=") {
  205. const assignmentPath = superProp.parentPath;
  206. const op = assignmentPath.node.operator.slice(0, -1);
  207. const value = assignmentPath.node.right;
  208. assignmentPath.node.operator = "=";
  209. if (superProp.node.computed) {
  210. const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
  211. assignmentPath.get("left").replaceWith(t.memberExpression(superProp.node.object, t.assignmentExpression("=", tmp, superProp.node.property), true));
  212. assignmentPath.get("right").replaceWith(t.binaryExpression(op, t.memberExpression(superProp.node.object, t.identifier(tmp.name), true), value));
  213. } else {
  214. assignmentPath.get("left").replaceWith(t.memberExpression(superProp.node.object, superProp.node.property));
  215. assignmentPath.get("right").replaceWith(t.binaryExpression(op, t.memberExpression(superProp.node.object, t.identifier(superProp.node.property.name)), value));
  216. }
  217. return [assignmentPath.get("left"), assignmentPath.get("right").get("left")];
  218. } else if (superProp.parentPath.isUpdateExpression()) {
  219. const updateExpr = superProp.parentPath;
  220. const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
  221. const computedKey = superProp.node.computed ? superProp.scope.generateDeclaredUidIdentifier("prop") : null;
  222. const parts = [t.assignmentExpression("=", tmp, t.memberExpression(superProp.node.object, computedKey ? t.assignmentExpression("=", computedKey, superProp.node.property) : superProp.node.property, superProp.node.computed)), t.assignmentExpression("=", t.memberExpression(superProp.node.object, computedKey ? t.identifier(computedKey.name) : superProp.node.property, superProp.node.computed), t.binaryExpression("+", t.identifier(tmp.name), t.numericLiteral(1)))];
  223. if (!superProp.parentPath.node.prefix) {
  224. parts.push(t.identifier(tmp.name));
  225. }
  226. updateExpr.replaceWith(t.sequenceExpression(parts));
  227. const left = updateExpr.get("expressions.0.right");
  228. const right = updateExpr.get("expressions.1.left");
  229. return [left, right];
  230. }
  231. return [superProp];
  232. }
  233. function hasSuperClass(thisEnvFn) {
  234. return thisEnvFn.isClassMethod() && !!thisEnvFn.parentPath.parentPath.node.superClass;
  235. }
  236. function getThisBinding(thisEnvFn, inConstructor) {
  237. return getBinding(thisEnvFn, "this", thisBinding => {
  238. if (!inConstructor || !hasSuperClass(thisEnvFn)) return t.thisExpression();
  239. const supers = new WeakSet();
  240. thisEnvFn.traverse({
  241. Function(child) {
  242. if (child.isArrowFunctionExpression()) return;
  243. child.skip();
  244. },
  245. ClassProperty(child) {
  246. child.skip();
  247. },
  248. CallExpression(child) {
  249. if (!child.get("callee").isSuper()) return;
  250. if (supers.has(child.node)) return;
  251. supers.add(child.node);
  252. child.replaceWithMultiple([child.node, t.assignmentExpression("=", t.identifier(thisBinding), t.identifier("this"))]);
  253. }
  254. });
  255. });
  256. }
  257. function getSuperBinding(thisEnvFn) {
  258. return getBinding(thisEnvFn, "supercall", () => {
  259. const argsBinding = thisEnvFn.scope.generateUidIdentifier("args");
  260. return t.arrowFunctionExpression([t.restElement(argsBinding)], t.callExpression(t.super(), [t.spreadElement(t.identifier(argsBinding.name))]));
  261. });
  262. }
  263. function getSuperPropBinding(thisEnvFn, isAssignment, propName) {
  264. const op = isAssignment ? "set" : "get";
  265. return getBinding(thisEnvFn, `superprop_${op}:${propName || ""}`, () => {
  266. const argsList = [];
  267. let fnBody;
  268. if (propName) {
  269. fnBody = t.memberExpression(t.super(), t.identifier(propName));
  270. } else {
  271. const method = thisEnvFn.scope.generateUidIdentifier("prop");
  272. argsList.unshift(method);
  273. fnBody = t.memberExpression(t.super(), t.identifier(method.name), true);
  274. }
  275. if (isAssignment) {
  276. const valueIdent = thisEnvFn.scope.generateUidIdentifier("value");
  277. argsList.push(valueIdent);
  278. fnBody = t.assignmentExpression("=", fnBody, t.identifier(valueIdent.name));
  279. }
  280. return t.arrowFunctionExpression(argsList, fnBody);
  281. });
  282. }
  283. function getBinding(thisEnvFn, key, init) {
  284. const cacheKey = "binding:" + key;
  285. let data = thisEnvFn.getData(cacheKey);
  286. if (!data) {
  287. const id = thisEnvFn.scope.generateUidIdentifier(key);
  288. data = id.name;
  289. thisEnvFn.setData(cacheKey, data);
  290. thisEnvFn.scope.push({
  291. id: id,
  292. init: init(data)
  293. });
  294. }
  295. return data;
  296. }
  297. function getScopeInformation(fnPath) {
  298. const thisPaths = [];
  299. const argumentsPaths = [];
  300. const newTargetPaths = [];
  301. const superProps = [];
  302. const superCalls = [];
  303. fnPath.traverse({
  304. ClassProperty(child) {
  305. child.skip();
  306. },
  307. Function(child) {
  308. if (child.isArrowFunctionExpression()) return;
  309. child.skip();
  310. },
  311. ThisExpression(child) {
  312. thisPaths.push(child);
  313. },
  314. JSXIdentifier(child) {
  315. if (child.node.name !== "this") return;
  316. if (!child.parentPath.isJSXMemberExpression({
  317. object: child.node
  318. }) && !child.parentPath.isJSXOpeningElement({
  319. name: child.node
  320. })) {
  321. return;
  322. }
  323. thisPaths.push(child);
  324. },
  325. CallExpression(child) {
  326. if (child.get("callee").isSuper()) superCalls.push(child);
  327. },
  328. MemberExpression(child) {
  329. if (child.get("object").isSuper()) superProps.push(child);
  330. },
  331. ReferencedIdentifier(child) {
  332. if (child.node.name !== "arguments") return;
  333. argumentsPaths.push(child);
  334. },
  335. MetaProperty(child) {
  336. if (!child.get("meta").isIdentifier({
  337. name: "new"
  338. })) return;
  339. if (!child.get("property").isIdentifier({
  340. name: "target"
  341. })) return;
  342. newTargetPaths.push(child);
  343. }
  344. });
  345. return {
  346. thisPaths,
  347. argumentsPaths,
  348. newTargetPaths,
  349. superProps,
  350. superCalls
  351. };
  352. }