transformClass.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = transformClass;
  6. var _helperFunctionName = require("@babel/helper-function-name");
  7. var _helperReplaceSupers = require("@babel/helper-replace-supers");
  8. var _helperOptimiseCallExpression = require("@babel/helper-optimise-call-expression");
  9. var _core = require("@babel/core");
  10. var _helperAnnotateAsPure = require("@babel/helper-annotate-as-pure");
  11. var _inlineCreateSuperHelpers = require("./inline-createSuper-helpers");
  12. function buildConstructor(classRef, constructorBody, node) {
  13. const func = _core.types.functionDeclaration(_core.types.cloneNode(classRef), [], constructorBody);
  14. _core.types.inherits(func, node);
  15. return func;
  16. }
  17. function transformClass(path, file, builtinClasses, isLoose, assumptions) {
  18. const classState = {
  19. parent: undefined,
  20. scope: undefined,
  21. node: undefined,
  22. path: undefined,
  23. file: undefined,
  24. classId: undefined,
  25. classRef: undefined,
  26. superFnId: undefined,
  27. superName: undefined,
  28. superReturns: [],
  29. isDerived: false,
  30. extendsNative: false,
  31. construct: undefined,
  32. constructorBody: undefined,
  33. userConstructor: undefined,
  34. userConstructorPath: undefined,
  35. hasConstructor: false,
  36. staticPropBody: [],
  37. body: [],
  38. superThises: [],
  39. pushedConstructor: false,
  40. pushedInherits: false,
  41. protoAlias: null,
  42. isLoose: false,
  43. dynamicKeys: new Map(),
  44. methods: {
  45. instance: {
  46. hasComputed: false,
  47. list: [],
  48. map: new Map()
  49. },
  50. static: {
  51. hasComputed: false,
  52. list: [],
  53. map: new Map()
  54. }
  55. }
  56. };
  57. const setState = newState => {
  58. Object.assign(classState, newState);
  59. };
  60. const findThisesVisitor = _core.traverse.visitors.merge([_helperReplaceSupers.environmentVisitor, {
  61. ThisExpression(path) {
  62. classState.superThises.push(path);
  63. }
  64. }]);
  65. function maybeCreateConstructor() {
  66. let hasConstructor = false;
  67. const paths = classState.path.get("body.body");
  68. for (const path of paths) {
  69. hasConstructor = path.equals("kind", "constructor");
  70. if (hasConstructor) break;
  71. }
  72. if (hasConstructor) return;
  73. let params, body;
  74. if (classState.isDerived) {
  75. const constructor = _core.template.expression.ast`
  76. (function () {
  77. super(...arguments);
  78. })
  79. `;
  80. params = constructor.params;
  81. body = constructor.body;
  82. } else {
  83. params = [];
  84. body = _core.types.blockStatement([]);
  85. }
  86. classState.path.get("body").unshiftContainer("body", _core.types.classMethod("constructor", _core.types.identifier("constructor"), params, body));
  87. }
  88. function buildBody() {
  89. maybeCreateConstructor();
  90. pushBody();
  91. verifyConstructor();
  92. if (classState.userConstructor) {
  93. const {
  94. constructorBody,
  95. userConstructor,
  96. construct
  97. } = classState;
  98. constructorBody.body.push(...userConstructor.body.body);
  99. _core.types.inherits(construct, userConstructor);
  100. _core.types.inherits(constructorBody, userConstructor.body);
  101. }
  102. pushDescriptors();
  103. }
  104. function pushBody() {
  105. const classBodyPaths = classState.path.get("body.body");
  106. for (const path of classBodyPaths) {
  107. const node = path.node;
  108. if (path.isClassProperty()) {
  109. throw path.buildCodeFrameError("Missing class properties transform.");
  110. }
  111. if (node.decorators) {
  112. throw path.buildCodeFrameError("Method has decorators, put the decorator plugin before the classes one.");
  113. }
  114. if (_core.types.isClassMethod(node)) {
  115. const isConstructor = node.kind === "constructor";
  116. const replaceSupers = new _helperReplaceSupers.default({
  117. methodPath: path,
  118. objectRef: classState.classRef,
  119. superRef: classState.superName,
  120. constantSuper: assumptions.constantSuper,
  121. file: classState.file,
  122. refToPreserve: classState.classRef
  123. });
  124. replaceSupers.replace();
  125. const superReturns = [];
  126. path.traverse(_core.traverse.visitors.merge([_helperReplaceSupers.environmentVisitor, {
  127. ReturnStatement(path) {
  128. if (!path.getFunctionParent().isArrowFunctionExpression()) {
  129. superReturns.push(path);
  130. }
  131. }
  132. }]));
  133. if (isConstructor) {
  134. pushConstructor(superReturns, node, path);
  135. } else {
  136. pushMethod(node, path);
  137. }
  138. }
  139. }
  140. }
  141. function pushDescriptors() {
  142. pushInheritsToBody();
  143. const {
  144. body
  145. } = classState;
  146. const props = {
  147. instance: null,
  148. static: null
  149. };
  150. for (const placement of ["static", "instance"]) {
  151. if (classState.methods[placement].list.length) {
  152. props[placement] = classState.methods[placement].list.map(desc => {
  153. const obj = _core.types.objectExpression([_core.types.objectProperty(_core.types.identifier("key"), desc.key)]);
  154. for (const kind of ["get", "set", "value"]) {
  155. if (desc[kind] != null) {
  156. obj.properties.push(_core.types.objectProperty(_core.types.identifier(kind), desc[kind]));
  157. }
  158. }
  159. return obj;
  160. });
  161. }
  162. }
  163. if (props.instance || props.static) {
  164. let args = [_core.types.cloneNode(classState.classRef), props.instance ? _core.types.arrayExpression(props.instance) : _core.types.nullLiteral(), props.static ? _core.types.arrayExpression(props.static) : _core.types.nullLiteral()];
  165. let lastNonNullIndex = 0;
  166. for (let i = 0; i < args.length; i++) {
  167. if (!_core.types.isNullLiteral(args[i])) lastNonNullIndex = i;
  168. }
  169. args = args.slice(0, lastNonNullIndex + 1);
  170. body.push(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper("createClass"), args)));
  171. }
  172. }
  173. function wrapSuperCall(bareSuper, superRef, thisRef, body) {
  174. const bareSuperNode = bareSuper.node;
  175. let call;
  176. if (assumptions.superIsCallableConstructor) {
  177. bareSuperNode.arguments.unshift(_core.types.thisExpression());
  178. if (bareSuperNode.arguments.length === 2 && _core.types.isSpreadElement(bareSuperNode.arguments[1]) && _core.types.isIdentifier(bareSuperNode.arguments[1].argument, {
  179. name: "arguments"
  180. })) {
  181. bareSuperNode.arguments[1] = bareSuperNode.arguments[1].argument;
  182. bareSuperNode.callee = _core.types.memberExpression(_core.types.cloneNode(superRef), _core.types.identifier("apply"));
  183. } else {
  184. bareSuperNode.callee = _core.types.memberExpression(_core.types.cloneNode(superRef), _core.types.identifier("call"));
  185. }
  186. call = _core.types.logicalExpression("||", bareSuperNode, _core.types.thisExpression());
  187. } else {
  188. call = (0, _helperOptimiseCallExpression.default)(_core.types.cloneNode(classState.superFnId), _core.types.thisExpression(), bareSuperNode.arguments, false);
  189. }
  190. if (bareSuper.parentPath.isExpressionStatement() && bareSuper.parentPath.container === body.node.body && body.node.body.length - 1 === bareSuper.parentPath.key) {
  191. if (classState.superThises.length) {
  192. call = _core.types.assignmentExpression("=", thisRef(), call);
  193. }
  194. bareSuper.parentPath.replaceWith(_core.types.returnStatement(call));
  195. } else {
  196. bareSuper.replaceWith(_core.types.assignmentExpression("=", thisRef(), call));
  197. }
  198. }
  199. function verifyConstructor() {
  200. if (!classState.isDerived) return;
  201. const path = classState.userConstructorPath;
  202. const body = path.get("body");
  203. path.traverse(findThisesVisitor);
  204. let thisRef = function () {
  205. const ref = path.scope.generateDeclaredUidIdentifier("this");
  206. thisRef = () => _core.types.cloneNode(ref);
  207. return ref;
  208. };
  209. for (const thisPath of classState.superThises) {
  210. const {
  211. node,
  212. parentPath
  213. } = thisPath;
  214. if (parentPath.isMemberExpression({
  215. object: node
  216. })) {
  217. thisPath.replaceWith(thisRef());
  218. continue;
  219. }
  220. thisPath.replaceWith(_core.types.callExpression(classState.file.addHelper("assertThisInitialized"), [thisRef()]));
  221. }
  222. const bareSupers = new Set();
  223. path.traverse(_core.traverse.visitors.merge([_helperReplaceSupers.environmentVisitor, {
  224. Super(path) {
  225. const {
  226. node,
  227. parentPath
  228. } = path;
  229. if (parentPath.isCallExpression({
  230. callee: node
  231. })) {
  232. bareSupers.add(parentPath);
  233. }
  234. }
  235. }]));
  236. let guaranteedSuperBeforeFinish = !!bareSupers.size;
  237. for (const bareSuper of bareSupers) {
  238. wrapSuperCall(bareSuper, classState.superName, thisRef, body);
  239. if (guaranteedSuperBeforeFinish) {
  240. bareSuper.find(function (parentPath) {
  241. if (parentPath === path) {
  242. return true;
  243. }
  244. if (parentPath.isLoop() || parentPath.isConditional() || parentPath.isArrowFunctionExpression()) {
  245. guaranteedSuperBeforeFinish = false;
  246. return true;
  247. }
  248. });
  249. }
  250. }
  251. let wrapReturn;
  252. if (classState.isLoose) {
  253. wrapReturn = returnArg => {
  254. const thisExpr = _core.types.callExpression(classState.file.addHelper("assertThisInitialized"), [thisRef()]);
  255. return returnArg ? _core.types.logicalExpression("||", returnArg, thisExpr) : thisExpr;
  256. };
  257. } else {
  258. wrapReturn = returnArg => _core.types.callExpression(classState.file.addHelper("possibleConstructorReturn"), [thisRef()].concat(returnArg || []));
  259. }
  260. const bodyPaths = body.get("body");
  261. if (!bodyPaths.length || !bodyPaths.pop().isReturnStatement()) {
  262. body.pushContainer("body", _core.types.returnStatement(guaranteedSuperBeforeFinish ? thisRef() : wrapReturn()));
  263. }
  264. for (const returnPath of classState.superReturns) {
  265. returnPath.get("argument").replaceWith(wrapReturn(returnPath.node.argument));
  266. }
  267. }
  268. function pushMethod(node, path) {
  269. const scope = path ? path.scope : classState.scope;
  270. if (node.kind === "method") {
  271. if (processMethod(node, scope)) return;
  272. }
  273. const placement = node.static ? "static" : "instance";
  274. const methods = classState.methods[placement];
  275. const descKey = node.kind === "method" ? "value" : node.kind;
  276. const key = _core.types.isNumericLiteral(node.key) || _core.types.isBigIntLiteral(node.key) ? _core.types.stringLiteral(String(node.key.value)) : _core.types.toComputedKey(node);
  277. let fn = _core.types.toExpression(node);
  278. if (_core.types.isStringLiteral(key)) {
  279. if (node.kind === "method") {
  280. fn = (0, _helperFunctionName.default)({
  281. id: key,
  282. node: node,
  283. scope
  284. });
  285. }
  286. } else {
  287. methods.hasComputed = true;
  288. }
  289. let descriptor;
  290. if (!methods.hasComputed && methods.map.has(key.value)) {
  291. descriptor = methods.map.get(key.value);
  292. descriptor[descKey] = fn;
  293. if (descKey === "value") {
  294. descriptor.get = null;
  295. descriptor.set = null;
  296. } else {
  297. descriptor.value = null;
  298. }
  299. } else {
  300. descriptor = {
  301. key: key,
  302. [descKey]: fn
  303. };
  304. methods.list.push(descriptor);
  305. if (!methods.hasComputed) {
  306. methods.map.set(key.value, descriptor);
  307. }
  308. }
  309. }
  310. function processMethod(node, scope) {
  311. if (assumptions.setClassMethods && !node.decorators) {
  312. let {
  313. classRef
  314. } = classState;
  315. if (!node.static) {
  316. insertProtoAliasOnce();
  317. classRef = classState.protoAlias;
  318. }
  319. const methodName = _core.types.memberExpression(_core.types.cloneNode(classRef), node.key, node.computed || _core.types.isLiteral(node.key));
  320. let func = _core.types.functionExpression(null, node.params, node.body, node.generator, node.async);
  321. _core.types.inherits(func, node);
  322. const key = _core.types.toComputedKey(node, node.key);
  323. if (_core.types.isStringLiteral(key)) {
  324. func = (0, _helperFunctionName.default)({
  325. node: func,
  326. id: key,
  327. scope
  328. });
  329. }
  330. const expr = _core.types.expressionStatement(_core.types.assignmentExpression("=", methodName, func));
  331. _core.types.inheritsComments(expr, node);
  332. classState.body.push(expr);
  333. return true;
  334. }
  335. return false;
  336. }
  337. function insertProtoAliasOnce() {
  338. if (classState.protoAlias === null) {
  339. setState({
  340. protoAlias: classState.scope.generateUidIdentifier("proto")
  341. });
  342. const classProto = _core.types.memberExpression(classState.classRef, _core.types.identifier("prototype"));
  343. const protoDeclaration = _core.types.variableDeclaration("var", [_core.types.variableDeclarator(classState.protoAlias, classProto)]);
  344. classState.body.push(protoDeclaration);
  345. }
  346. }
  347. function pushConstructor(superReturns, method, path) {
  348. setState({
  349. userConstructorPath: path,
  350. userConstructor: method,
  351. hasConstructor: true,
  352. superReturns
  353. });
  354. const {
  355. construct
  356. } = classState;
  357. _core.types.inheritsComments(construct, method);
  358. construct.params = method.params;
  359. _core.types.inherits(construct.body, method.body);
  360. construct.body.directives = method.body.directives;
  361. pushConstructorToBody();
  362. }
  363. function pushConstructorToBody() {
  364. if (classState.pushedConstructor) return;
  365. classState.pushedConstructor = true;
  366. if (classState.hasInstanceDescriptors || classState.hasStaticDescriptors) {
  367. pushDescriptors();
  368. }
  369. classState.body.push(classState.construct);
  370. pushInheritsToBody();
  371. }
  372. function pushInheritsToBody() {
  373. if (!classState.isDerived || classState.pushedInherits) return;
  374. const superFnId = path.scope.generateUidIdentifier("super");
  375. setState({
  376. pushedInherits: true,
  377. superFnId
  378. });
  379. if (!assumptions.superIsCallableConstructor) {
  380. classState.body.unshift(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(superFnId, _core.types.callExpression((0, _inlineCreateSuperHelpers.default)(classState.file), [_core.types.cloneNode(classState.classRef)]))]));
  381. }
  382. classState.body.unshift(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper(classState.isLoose ? "inheritsLoose" : "inherits"), [_core.types.cloneNode(classState.classRef), _core.types.cloneNode(classState.superName)])));
  383. }
  384. function extractDynamicKeys() {
  385. const {
  386. dynamicKeys,
  387. node,
  388. scope
  389. } = classState;
  390. for (const elem of node.body.body) {
  391. if (!_core.types.isClassMethod(elem) || !elem.computed) continue;
  392. if (scope.isPure(elem.key, true)) continue;
  393. const id = scope.generateUidIdentifierBasedOnNode(elem.key);
  394. dynamicKeys.set(id.name, elem.key);
  395. elem.key = id;
  396. }
  397. }
  398. function setupClosureParamsArgs() {
  399. const {
  400. superName,
  401. dynamicKeys
  402. } = classState;
  403. const closureParams = [];
  404. const closureArgs = [];
  405. if (classState.isDerived) {
  406. let arg = _core.types.cloneNode(superName);
  407. if (classState.extendsNative) {
  408. arg = _core.types.callExpression(classState.file.addHelper("wrapNativeSuper"), [arg]);
  409. (0, _helperAnnotateAsPure.default)(arg);
  410. }
  411. const param = classState.scope.generateUidIdentifierBasedOnNode(superName);
  412. closureParams.push(param);
  413. closureArgs.push(arg);
  414. setState({
  415. superName: _core.types.cloneNode(param)
  416. });
  417. }
  418. for (const [name, value] of dynamicKeys) {
  419. closureParams.push(_core.types.identifier(name));
  420. closureArgs.push(value);
  421. }
  422. return {
  423. closureParams,
  424. closureArgs
  425. };
  426. }
  427. function classTransformer(path, file, builtinClasses, isLoose) {
  428. setState({
  429. parent: path.parent,
  430. scope: path.scope,
  431. node: path.node,
  432. path,
  433. file,
  434. isLoose
  435. });
  436. setState({
  437. classId: classState.node.id,
  438. classRef: classState.node.id ? _core.types.identifier(classState.node.id.name) : classState.scope.generateUidIdentifier("class"),
  439. superName: classState.node.superClass,
  440. isDerived: !!classState.node.superClass,
  441. constructorBody: _core.types.blockStatement([])
  442. });
  443. setState({
  444. extendsNative: classState.isDerived && builtinClasses.has(classState.superName.name) && !classState.scope.hasBinding(classState.superName.name, true)
  445. });
  446. const {
  447. classRef,
  448. node,
  449. constructorBody
  450. } = classState;
  451. setState({
  452. construct: buildConstructor(classRef, constructorBody, node)
  453. });
  454. extractDynamicKeys();
  455. const {
  456. body
  457. } = classState;
  458. const {
  459. closureParams,
  460. closureArgs
  461. } = setupClosureParamsArgs();
  462. buildBody();
  463. if (!assumptions.noClassCalls) {
  464. constructorBody.body.unshift(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper("classCallCheck"), [_core.types.thisExpression(), _core.types.cloneNode(classState.classRef)])));
  465. }
  466. body.push(...classState.staticPropBody.map(fn => fn(_core.types.cloneNode(classState.classRef))));
  467. const isStrict = path.isInStrictMode();
  468. let constructorOnly = classState.classId && body.length === 1;
  469. if (constructorOnly && !isStrict) {
  470. for (const param of classState.construct.params) {
  471. if (!_core.types.isIdentifier(param)) {
  472. constructorOnly = false;
  473. break;
  474. }
  475. }
  476. }
  477. const directives = constructorOnly ? body[0].body.directives : [];
  478. if (!isStrict) {
  479. directives.push(_core.types.directive(_core.types.directiveLiteral("use strict")));
  480. }
  481. if (constructorOnly) {
  482. return _core.types.toExpression(body[0]);
  483. }
  484. body.push(_core.types.returnStatement(_core.types.cloneNode(classState.classRef)));
  485. const container = _core.types.arrowFunctionExpression(closureParams, _core.types.blockStatement(body, directives));
  486. return _core.types.callExpression(container, closureArgs);
  487. }
  488. return classTransformer(path, file, builtinClasses, isLoose);
  489. }