transformClass.js 18 KB

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