transformClass.js 18 KB

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