conversion.js 16 KB

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