conversion.js 15 KB

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