transformClass.js 18 KB

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