conversion.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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 superParentPath = superProp.parentPath;
  215. const isAssignment = superParentPath.isAssignmentExpression({
  216. left: superProp.node
  217. });
  218. const isCall = superParentPath.isCallExpression({
  219. callee: superProp.node
  220. });
  221. const superBinding = getSuperPropBinding(thisEnvFn, isAssignment, key);
  222. const args = [];
  223. if (superProp.node.computed) {
  224. args.push(superProp.get("property").node);
  225. }
  226. if (isAssignment) {
  227. const value = superParentPath.node.right;
  228. args.push(value);
  229. }
  230. const call = callExpression(identifier(superBinding), args);
  231. if (isCall) {
  232. superParentPath.unshiftContainer("arguments", thisExpression());
  233. superProp.replaceWith(memberExpression(call, identifier("call")));
  234. thisPaths.push(superParentPath.get("arguments.0"));
  235. } else if (isAssignment) {
  236. superParentPath.replaceWith(call);
  237. } else {
  238. superProp.replaceWith(call);
  239. }
  240. });
  241. }
  242. let thisBinding;
  243. if (thisPaths.length > 0 || !noNewArrows) {
  244. thisBinding = getThisBinding(thisEnvFn, inConstructor);
  245. if (noNewArrows || inConstructor && hasSuperClass(thisEnvFn)) {
  246. thisPaths.forEach(thisChild => {
  247. const thisRef = thisChild.isJSX() ? jsxIdentifier(thisBinding) : identifier(thisBinding);
  248. thisRef.loc = thisChild.node.loc;
  249. thisChild.replaceWith(thisRef);
  250. });
  251. if (!noNewArrows) thisBinding = null;
  252. }
  253. }
  254. return {
  255. thisBinding,
  256. fnPath
  257. };
  258. }
  259. function isLogicalOp(op) {
  260. return LOGICAL_OPERATORS.includes(op);
  261. }
  262. function standardizeSuperProperty(superProp) {
  263. if (superProp.parentPath.isAssignmentExpression() && superProp.parentPath.node.operator !== "=") {
  264. const assignmentPath = superProp.parentPath;
  265. const op = assignmentPath.node.operator.slice(0, -1);
  266. const value = assignmentPath.node.right;
  267. const isLogicalAssignment = isLogicalOp(op);
  268. if (superProp.node.computed) {
  269. const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
  270. const object = superProp.node.object;
  271. const property = superProp.node.property;
  272. assignmentPath.get("left").replaceWith(memberExpression(object, assignmentExpression("=", tmp, property), true));
  273. assignmentPath.get("right").replaceWith(rightExpression(isLogicalAssignment ? "=" : op, memberExpression(object, identifier(tmp.name), true), value));
  274. } else {
  275. const object = superProp.node.object;
  276. const property = superProp.node.property;
  277. assignmentPath.get("left").replaceWith(memberExpression(object, property));
  278. assignmentPath.get("right").replaceWith(rightExpression(isLogicalAssignment ? "=" : op, memberExpression(object, identifier(property.name)), value));
  279. }
  280. if (isLogicalAssignment) {
  281. assignmentPath.replaceWith(logicalExpression(op, assignmentPath.node.left, assignmentPath.node.right));
  282. } else {
  283. assignmentPath.node.operator = "=";
  284. }
  285. return [assignmentPath.get("left"), assignmentPath.get("right").get("left")];
  286. } else if (superProp.parentPath.isUpdateExpression()) {
  287. const updateExpr = superProp.parentPath;
  288. const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
  289. const computedKey = superProp.node.computed ? superProp.scope.generateDeclaredUidIdentifier("prop") : null;
  290. 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)))];
  291. if (!superProp.parentPath.node.prefix) {
  292. parts.push(identifier(tmp.name));
  293. }
  294. updateExpr.replaceWith(sequenceExpression(parts));
  295. const left = updateExpr.get("expressions.0.right");
  296. const right = updateExpr.get("expressions.1.left");
  297. return [left, right];
  298. }
  299. return [superProp];
  300. function rightExpression(op, left, right) {
  301. if (op === "=") {
  302. return assignmentExpression("=", left, right);
  303. } else {
  304. return binaryExpression(op, left, right);
  305. }
  306. }
  307. }
  308. function hasSuperClass(thisEnvFn) {
  309. return thisEnvFn.isClassMethod() && !!thisEnvFn.parentPath.parentPath.node.superClass;
  310. }
  311. const assignSuperThisVisitor = (0, _visitors.merge)([{
  312. CallExpression(child, {
  313. supers,
  314. thisBinding
  315. }) {
  316. if (!child.get("callee").isSuper()) return;
  317. if (supers.has(child.node)) return;
  318. supers.add(child.node);
  319. child.replaceWithMultiple([child.node, assignmentExpression("=", identifier(thisBinding), identifier("this"))]);
  320. }
  321. }, _helperEnvironmentVisitor.default]);
  322. function getThisBinding(thisEnvFn, inConstructor) {
  323. return getBinding(thisEnvFn, "this", thisBinding => {
  324. if (!inConstructor || !hasSuperClass(thisEnvFn)) return thisExpression();
  325. thisEnvFn.traverse(assignSuperThisVisitor, {
  326. supers: new WeakSet(),
  327. thisBinding
  328. });
  329. });
  330. }
  331. function getSuperBinding(thisEnvFn) {
  332. return getBinding(thisEnvFn, "supercall", () => {
  333. const argsBinding = thisEnvFn.scope.generateUidIdentifier("args");
  334. return arrowFunctionExpression([restElement(argsBinding)], callExpression(_super(), [spreadElement(identifier(argsBinding.name))]));
  335. });
  336. }
  337. function getSuperPropBinding(thisEnvFn, isAssignment, propName) {
  338. const op = isAssignment ? "set" : "get";
  339. return getBinding(thisEnvFn, `superprop_${op}:${propName || ""}`, () => {
  340. const argsList = [];
  341. let fnBody;
  342. if (propName) {
  343. fnBody = memberExpression(_super(), identifier(propName));
  344. } else {
  345. const method = thisEnvFn.scope.generateUidIdentifier("prop");
  346. argsList.unshift(method);
  347. fnBody = memberExpression(_super(), identifier(method.name), true);
  348. }
  349. if (isAssignment) {
  350. const valueIdent = thisEnvFn.scope.generateUidIdentifier("value");
  351. argsList.push(valueIdent);
  352. fnBody = assignmentExpression("=", fnBody, identifier(valueIdent.name));
  353. }
  354. return arrowFunctionExpression(argsList, fnBody);
  355. });
  356. }
  357. function getBinding(thisEnvFn, key, init) {
  358. const cacheKey = "binding:" + key;
  359. let data = thisEnvFn.getData(cacheKey);
  360. if (!data) {
  361. const id = thisEnvFn.scope.generateUidIdentifier(key);
  362. data = id.name;
  363. thisEnvFn.setData(cacheKey, data);
  364. thisEnvFn.scope.push({
  365. id: id,
  366. init: init(data)
  367. });
  368. }
  369. return data;
  370. }
  371. const getScopeInformationVisitor = (0, _visitors.merge)([{
  372. ThisExpression(child, {
  373. thisPaths
  374. }) {
  375. thisPaths.push(child);
  376. },
  377. JSXIdentifier(child, {
  378. thisPaths
  379. }) {
  380. if (child.node.name !== "this") return;
  381. if (!child.parentPath.isJSXMemberExpression({
  382. object: child.node
  383. }) && !child.parentPath.isJSXOpeningElement({
  384. name: child.node
  385. })) {
  386. return;
  387. }
  388. thisPaths.push(child);
  389. },
  390. CallExpression(child, {
  391. superCalls
  392. }) {
  393. if (child.get("callee").isSuper()) superCalls.push(child);
  394. },
  395. MemberExpression(child, {
  396. superProps
  397. }) {
  398. if (child.get("object").isSuper()) superProps.push(child);
  399. },
  400. Identifier(child, {
  401. argumentsPaths
  402. }) {
  403. if (!child.isReferencedIdentifier({
  404. name: "arguments"
  405. })) return;
  406. let curr = child.scope;
  407. do {
  408. if (curr.hasOwnBinding("arguments")) {
  409. curr.rename("arguments");
  410. return;
  411. }
  412. if (curr.path.isFunction() && !curr.path.isArrowFunctionExpression()) {
  413. break;
  414. }
  415. } while (curr = curr.parent);
  416. argumentsPaths.push(child);
  417. },
  418. MetaProperty(child, {
  419. newTargetPaths
  420. }) {
  421. if (!child.get("meta").isIdentifier({
  422. name: "new"
  423. })) return;
  424. if (!child.get("property").isIdentifier({
  425. name: "target"
  426. })) return;
  427. newTargetPaths.push(child);
  428. }
  429. }, _helperEnvironmentVisitor.default]);
  430. function getScopeInformation(fnPath) {
  431. const thisPaths = [];
  432. const argumentsPaths = [];
  433. const newTargetPaths = [];
  434. const superProps = [];
  435. const superCalls = [];
  436. fnPath.traverse(getScopeInformationVisitor, {
  437. thisPaths,
  438. argumentsPaths,
  439. newTargetPaths,
  440. superProps,
  441. superCalls
  442. });
  443. return {
  444. thisPaths,
  445. argumentsPaths,
  446. newTargetPaths,
  447. superProps,
  448. superCalls
  449. };
  450. }