conversion.js 15 KB

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