conversion.js 14 KB

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