conversion.js 14 KB

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