conversion.js 16 KB

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