transformClass.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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, 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. 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),
  169. props.instance ? _core.types.arrayExpression(props.instance) : _core.types.nullLiteral(),
  170. props.static ? _core.types.arrayExpression(props.static) : _core.types.nullLiteral()];
  171. let lastNonNullIndex = 0;
  172. for (let i = 0; i < args.length; i++) {
  173. if (!_core.types.isNullLiteral(args[i])) lastNonNullIndex = i;
  174. }
  175. args = args.slice(0, lastNonNullIndex + 1);
  176. body.push(_core.types.expressionStatement(createClassHelper(args)));
  177. classState.pushedCreateClass = true;
  178. }
  179. }
  180. function wrapSuperCall(bareSuper, superRef, thisRef, body) {
  181. const bareSuperNode = bareSuper.node;
  182. let call;
  183. if (assumptions.superIsCallableConstructor) {
  184. bareSuperNode.arguments.unshift(_core.types.thisExpression());
  185. if (bareSuperNode.arguments.length === 2 && _core.types.isSpreadElement(bareSuperNode.arguments[1]) && _core.types.isIdentifier(bareSuperNode.arguments[1].argument, {
  186. name: "arguments"
  187. })) {
  188. bareSuperNode.arguments[1] = bareSuperNode.arguments[1].argument;
  189. bareSuperNode.callee = _core.types.memberExpression(_core.types.cloneNode(superRef), _core.types.identifier("apply"));
  190. } else {
  191. bareSuperNode.callee = _core.types.memberExpression(_core.types.cloneNode(superRef), _core.types.identifier("call"));
  192. }
  193. call = _core.types.logicalExpression("||", bareSuperNode, _core.types.thisExpression());
  194. } else {
  195. call = (0, _helperOptimiseCallExpression.default)(_core.types.cloneNode(classState.superFnId), _core.types.thisExpression(), bareSuperNode.arguments, false);
  196. }
  197. if (bareSuper.parentPath.isExpressionStatement() && bareSuper.parentPath.container === body.node.body && body.node.body.length - 1 === bareSuper.parentPath.key) {
  198. if (classState.superThises.length) {
  199. call = _core.types.assignmentExpression("=", thisRef(), call);
  200. }
  201. bareSuper.parentPath.replaceWith(_core.types.returnStatement(call));
  202. } else {
  203. bareSuper.replaceWith(_core.types.assignmentExpression("=", thisRef(), call));
  204. }
  205. }
  206. function verifyConstructor() {
  207. if (!classState.isDerived) return;
  208. const path = classState.userConstructorPath;
  209. const body = path.get("body");
  210. path.traverse(findThisesVisitor);
  211. let thisRef = function () {
  212. const ref = path.scope.generateDeclaredUidIdentifier("this");
  213. thisRef = () => _core.types.cloneNode(ref);
  214. return ref;
  215. };
  216. for (const thisPath of classState.superThises) {
  217. const {
  218. node,
  219. parentPath
  220. } = thisPath;
  221. if (parentPath.isMemberExpression({
  222. object: node
  223. })) {
  224. thisPath.replaceWith(thisRef());
  225. continue;
  226. }
  227. thisPath.replaceWith(_core.types.callExpression(classState.file.addHelper("assertThisInitialized"), [thisRef()]));
  228. }
  229. const bareSupers = [];
  230. path.traverse(_core.traverse.visitors.merge([_helperEnvironmentVisitor.default, {
  231. Super(path) {
  232. const {
  233. node,
  234. parentPath
  235. } = path;
  236. if (parentPath.isCallExpression({
  237. callee: node
  238. })) {
  239. bareSupers.unshift(parentPath);
  240. }
  241. }
  242. }]));
  243. let guaranteedSuperBeforeFinish = !!bareSupers.length;
  244. for (const bareSuper of bareSupers) {
  245. wrapSuperCall(bareSuper, classState.superName, thisRef, body);
  246. if (guaranteedSuperBeforeFinish) {
  247. bareSuper.find(function (parentPath) {
  248. if (parentPath === path) {
  249. return true;
  250. }
  251. if (parentPath.isLoop() || parentPath.isConditional() || parentPath.isArrowFunctionExpression()) {
  252. guaranteedSuperBeforeFinish = false;
  253. return true;
  254. }
  255. });
  256. }
  257. }
  258. let wrapReturn;
  259. if (classState.isLoose) {
  260. wrapReturn = returnArg => {
  261. const thisExpr = _core.types.callExpression(classState.file.addHelper("assertThisInitialized"), [thisRef()]);
  262. return returnArg ? _core.types.logicalExpression("||", returnArg, thisExpr) : thisExpr;
  263. };
  264. } else {
  265. wrapReturn = returnArg => {
  266. const returnParams = [thisRef()];
  267. if (returnArg != null) {
  268. returnParams.push(returnArg);
  269. }
  270. return _core.types.callExpression(classState.file.addHelper("possibleConstructorReturn"), returnParams);
  271. };
  272. }
  273. const bodyPaths = body.get("body");
  274. if (!bodyPaths.length || !bodyPaths.pop().isReturnStatement()) {
  275. body.pushContainer("body", _core.types.returnStatement(guaranteedSuperBeforeFinish ? thisRef() : wrapReturn()));
  276. }
  277. for (const returnPath of classState.superReturns) {
  278. returnPath.get("argument").replaceWith(wrapReturn(returnPath.node.argument));
  279. }
  280. }
  281. function pushMethod(node, path) {
  282. const scope = path ? path.scope : classState.scope;
  283. if (node.kind === "method") {
  284. if (processMethod(node, scope)) return;
  285. }
  286. const placement = node.static ? "static" : "instance";
  287. const methods = classState.methods[placement];
  288. const descKey = node.kind === "method" ? "value" : node.kind;
  289. const key = _core.types.isNumericLiteral(node.key) || _core.types.isBigIntLiteral(node.key) ? _core.types.stringLiteral(String(node.key.value)) : _core.types.toComputedKey(node);
  290. let fn = _core.types.toExpression(node);
  291. if (_core.types.isStringLiteral(key)) {
  292. if (node.kind === "method") {
  293. var _nameFunction;
  294. fn = (_nameFunction = (0, _helperFunctionName.default)(
  295. {
  296. id: key,
  297. node: node,
  298. scope
  299. }, undefined, supportUnicodeId)) != null ? _nameFunction : fn;
  300. }
  301. } else {
  302. methods.hasComputed = true;
  303. }
  304. let descriptor;
  305. if (!methods.hasComputed && methods.map.has(key.value)) {
  306. descriptor = methods.map.get(key.value);
  307. descriptor[descKey] = fn;
  308. if (descKey === "value") {
  309. descriptor.get = null;
  310. descriptor.set = null;
  311. } else {
  312. descriptor.value = null;
  313. }
  314. } else {
  315. descriptor = {
  316. key:
  317. key,
  318. [descKey]: fn
  319. };
  320. methods.list.push(descriptor);
  321. if (!methods.hasComputed) {
  322. methods.map.set(key.value, descriptor);
  323. }
  324. }
  325. }
  326. function processMethod(node, scope) {
  327. if (assumptions.setClassMethods && !node.decorators) {
  328. let {
  329. classRef
  330. } = classState;
  331. if (!node.static) {
  332. insertProtoAliasOnce();
  333. classRef = classState.protoAlias;
  334. }
  335. const methodName = _core.types.memberExpression(_core.types.cloneNode(classRef), node.key, node.computed || _core.types.isLiteral(node.key));
  336. let func = _core.types.functionExpression(null,
  337. node.params, node.body, node.generator, node.async);
  338. _core.types.inherits(func, node);
  339. const key = _core.types.toComputedKey(node, node.key);
  340. if (_core.types.isStringLiteral(key)) {
  341. var _nameFunction2;
  342. func = (_nameFunction2 = (0, _helperFunctionName.default)({
  343. node: func,
  344. id: key,
  345. scope
  346. }, undefined, supportUnicodeId)) != null ? _nameFunction2 : func;
  347. }
  348. const expr = _core.types.expressionStatement(_core.types.assignmentExpression("=", methodName, func));
  349. _core.types.inheritsComments(expr, node);
  350. classState.body.push(expr);
  351. return true;
  352. }
  353. return false;
  354. }
  355. function insertProtoAliasOnce() {
  356. if (classState.protoAlias === null) {
  357. setState({
  358. protoAlias: classState.scope.generateUidIdentifier("proto")
  359. });
  360. const classProto = _core.types.memberExpression(classState.classRef, _core.types.identifier("prototype"));
  361. const protoDeclaration = _core.types.variableDeclaration("var", [_core.types.variableDeclarator(classState.protoAlias, classProto)]);
  362. classState.body.push(protoDeclaration);
  363. }
  364. }
  365. function pushConstructor(superReturns, method, path) {
  366. setState({
  367. userConstructorPath: path,
  368. userConstructor: method,
  369. hasConstructor: true,
  370. superReturns
  371. });
  372. const {
  373. construct
  374. } = classState;
  375. _core.types.inheritsComments(construct, method);
  376. construct.params = method.params;
  377. _core.types.inherits(construct.body, method.body);
  378. construct.body.directives = method.body.directives;
  379. pushConstructorToBody();
  380. }
  381. function pushConstructorToBody() {
  382. if (classState.pushedConstructor) return;
  383. classState.pushedConstructor = true;
  384. if (classState.hasInstanceDescriptors || classState.hasStaticDescriptors) {
  385. pushDescriptors();
  386. }
  387. classState.body.push(classState.construct);
  388. pushInheritsToBody();
  389. }
  390. function pushInheritsToBody() {
  391. if (!classState.isDerived || classState.pushedInherits) return;
  392. const superFnId = path.scope.generateUidIdentifier("super");
  393. setState({
  394. pushedInherits: true,
  395. superFnId
  396. });
  397. if (!assumptions.superIsCallableConstructor) {
  398. classState.body.unshift(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(superFnId, _core.types.callExpression((0, _inlineCreateSuperHelpers.default)(classState.file), [_core.types.cloneNode(classState.classRef)]))]));
  399. }
  400. 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)])));
  401. }
  402. function extractDynamicKeys() {
  403. const {
  404. dynamicKeys,
  405. node,
  406. scope
  407. } = classState;
  408. for (const elem of node.body.body) {
  409. if (!_core.types.isClassMethod(elem) || !elem.computed) continue;
  410. if (scope.isPure(elem.key, true)) continue;
  411. const id = scope.generateUidIdentifierBasedOnNode(elem.key);
  412. dynamicKeys.set(id.name, elem.key);
  413. elem.key = id;
  414. }
  415. }
  416. function setupClosureParamsArgs() {
  417. const {
  418. superName,
  419. dynamicKeys
  420. } = classState;
  421. const closureParams = [];
  422. const closureArgs = [];
  423. if (classState.isDerived) {
  424. let arg = _core.types.cloneNode(superName);
  425. if (classState.extendsNative) {
  426. arg = _core.types.callExpression(classState.file.addHelper("wrapNativeSuper"), [arg]);
  427. (0, _helperAnnotateAsPure.default)(arg);
  428. }
  429. const param = classState.scope.generateUidIdentifierBasedOnNode(superName);
  430. closureParams.push(param);
  431. closureArgs.push(arg);
  432. setState({
  433. superName: _core.types.cloneNode(param)
  434. });
  435. }
  436. for (const [name, value] of dynamicKeys) {
  437. closureParams.push(_core.types.identifier(name));
  438. closureArgs.push(value);
  439. }
  440. return {
  441. closureParams,
  442. closureArgs
  443. };
  444. }
  445. function classTransformer(path, file, builtinClasses, isLoose) {
  446. setState({
  447. parent: path.parent,
  448. scope: path.scope,
  449. node: path.node,
  450. path,
  451. file,
  452. isLoose
  453. });
  454. setState({
  455. classId: classState.node.id,
  456. classRef: classState.node.id ? _core.types.identifier(classState.node.id.name) : classState.scope.generateUidIdentifier("class"),
  457. superName: classState.node.superClass,
  458. isDerived: !!classState.node.superClass,
  459. constructorBody: _core.types.blockStatement([])
  460. });
  461. setState({
  462. extendsNative: _core.types.isIdentifier(classState.superName) && builtinClasses.has(classState.superName.name) && !classState.scope.hasBinding(classState.superName.name, true)
  463. });
  464. const {
  465. classRef,
  466. node,
  467. constructorBody
  468. } = classState;
  469. setState({
  470. construct: buildConstructor(classRef, constructorBody, node)
  471. });
  472. extractDynamicKeys();
  473. const {
  474. body
  475. } = classState;
  476. const {
  477. closureParams,
  478. closureArgs
  479. } = setupClosureParamsArgs();
  480. buildBody();
  481. if (!assumptions.noClassCalls) {
  482. constructorBody.body.unshift(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper("classCallCheck"), [_core.types.thisExpression(), _core.types.cloneNode(classState.classRef)])));
  483. }
  484. const isStrict = path.isInStrictMode();
  485. let constructorOnly = classState.classId && body.length === 1;
  486. if (constructorOnly && !isStrict) {
  487. for (const param of classState.construct.params) {
  488. if (!_core.types.isIdentifier(param)) {
  489. constructorOnly = false;
  490. break;
  491. }
  492. }
  493. }
  494. const directives = constructorOnly ? body[0].body.directives : [];
  495. if (!isStrict) {
  496. directives.push(_core.types.directive(_core.types.directiveLiteral("use strict")));
  497. }
  498. if (constructorOnly) {
  499. const expr = _core.types.toExpression(body[0]);
  500. return classState.isLoose ? expr : createClassHelper([expr]);
  501. }
  502. let returnArg = _core.types.cloneNode(classState.classRef);
  503. if (!classState.pushedCreateClass && !classState.isLoose) {
  504. returnArg = createClassHelper([returnArg]);
  505. }
  506. body.push(_core.types.returnStatement(returnArg));
  507. const container = _core.types.arrowFunctionExpression(closureParams, _core.types.blockStatement(body, directives));
  508. return _core.types.callExpression(container, closureArgs);
  509. }
  510. return classTransformer(path, file, builtinClasses, isLoose);
  511. }
  512. //# sourceMappingURL=transformClass.js.map