You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

427 lines
14 KiB

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