transformClass.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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), 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. var _nameFunction;
  292. fn = (_nameFunction = (0, _helperFunctionName.default)({
  293. id: key,
  294. node: node,
  295. scope
  296. }, undefined, supportUnicodeId)) != null ? _nameFunction : fn;
  297. }
  298. } else {
  299. methods.hasComputed = true;
  300. }
  301. let descriptor;
  302. if (!methods.hasComputed && methods.map.has(key.value)) {
  303. descriptor = methods.map.get(key.value);
  304. descriptor[descKey] = fn;
  305. if (descKey === "value") {
  306. descriptor.get = null;
  307. descriptor.set = null;
  308. } else {
  309. descriptor.value = null;
  310. }
  311. } else {
  312. descriptor = {
  313. key: key,
  314. [descKey]: fn
  315. };
  316. methods.list.push(descriptor);
  317. if (!methods.hasComputed) {
  318. methods.map.set(key.value, descriptor);
  319. }
  320. }
  321. }
  322. function processMethod(node, scope) {
  323. if (assumptions.setClassMethods && !node.decorators) {
  324. let {
  325. classRef
  326. } = classState;
  327. if (!node.static) {
  328. insertProtoAliasOnce();
  329. classRef = classState.protoAlias;
  330. }
  331. const methodName = _core.types.memberExpression(_core.types.cloneNode(classRef), node.key, node.computed || _core.types.isLiteral(node.key));
  332. let func = _core.types.functionExpression(null, node.params, node.body, node.generator, node.async);
  333. _core.types.inherits(func, node);
  334. const key = _core.types.toComputedKey(node, node.key);
  335. if (_core.types.isStringLiteral(key)) {
  336. var _nameFunction2;
  337. func = (_nameFunction2 = (0, _helperFunctionName.default)({
  338. node: func,
  339. id: key,
  340. scope
  341. }, undefined, supportUnicodeId)) != null ? _nameFunction2 : func;
  342. }
  343. const expr = _core.types.expressionStatement(_core.types.assignmentExpression("=", methodName, func));
  344. _core.types.inheritsComments(expr, node);
  345. classState.body.push(expr);
  346. return true;
  347. }
  348. return false;
  349. }
  350. function insertProtoAliasOnce() {
  351. if (classState.protoAlias === null) {
  352. setState({
  353. protoAlias: classState.scope.generateUidIdentifier("proto")
  354. });
  355. const classProto = _core.types.memberExpression(classState.classRef, _core.types.identifier("prototype"));
  356. const protoDeclaration = _core.types.variableDeclaration("var", [_core.types.variableDeclarator(classState.protoAlias, classProto)]);
  357. classState.body.push(protoDeclaration);
  358. }
  359. }
  360. function pushConstructor(superReturns, method, path) {
  361. setState({
  362. userConstructorPath: path,
  363. userConstructor: method,
  364. hasConstructor: true,
  365. superReturns
  366. });
  367. const {
  368. construct
  369. } = classState;
  370. _core.types.inheritsComments(construct, method);
  371. construct.params = method.params;
  372. _core.types.inherits(construct.body, method.body);
  373. construct.body.directives = method.body.directives;
  374. pushConstructorToBody();
  375. }
  376. function pushConstructorToBody() {
  377. if (classState.pushedConstructor) return;
  378. classState.pushedConstructor = true;
  379. if (classState.hasInstanceDescriptors || classState.hasStaticDescriptors) {
  380. pushDescriptors();
  381. }
  382. classState.body.push(classState.construct);
  383. pushInheritsToBody();
  384. }
  385. function pushInheritsToBody() {
  386. if (!classState.isDerived || classState.pushedInherits) return;
  387. const superFnId = path.scope.generateUidIdentifier("super");
  388. setState({
  389. pushedInherits: true,
  390. superFnId
  391. });
  392. if (!assumptions.superIsCallableConstructor) {
  393. classState.body.unshift(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(superFnId, _core.types.callExpression((0, _inlineCreateSuperHelpers.default)(classState.file), [_core.types.cloneNode(classState.classRef)]))]));
  394. }
  395. 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)])));
  396. }
  397. function extractDynamicKeys() {
  398. const {
  399. dynamicKeys,
  400. node,
  401. scope
  402. } = classState;
  403. for (const elem of node.body.body) {
  404. if (!_core.types.isClassMethod(elem) || !elem.computed) continue;
  405. if (scope.isPure(elem.key, true)) continue;
  406. const id = scope.generateUidIdentifierBasedOnNode(elem.key);
  407. dynamicKeys.set(id.name, elem.key);
  408. elem.key = id;
  409. }
  410. }
  411. function setupClosureParamsArgs() {
  412. const {
  413. superName,
  414. dynamicKeys
  415. } = classState;
  416. const closureParams = [];
  417. const closureArgs = [];
  418. if (classState.isDerived) {
  419. let arg = _core.types.cloneNode(superName);
  420. if (classState.extendsNative) {
  421. arg = _core.types.callExpression(classState.file.addHelper("wrapNativeSuper"), [arg]);
  422. (0, _helperAnnotateAsPure.default)(arg);
  423. }
  424. const param = classState.scope.generateUidIdentifierBasedOnNode(superName);
  425. closureParams.push(param);
  426. closureArgs.push(arg);
  427. setState({
  428. superName: _core.types.cloneNode(param)
  429. });
  430. }
  431. for (const [name, value] of dynamicKeys) {
  432. closureParams.push(_core.types.identifier(name));
  433. closureArgs.push(value);
  434. }
  435. return {
  436. closureParams,
  437. closureArgs
  438. };
  439. }
  440. function classTransformer(path, file, builtinClasses, isLoose) {
  441. setState({
  442. parent: path.parent,
  443. scope: path.scope,
  444. node: path.node,
  445. path,
  446. file,
  447. isLoose
  448. });
  449. setState({
  450. classId: classState.node.id,
  451. classRef: classState.node.id ? _core.types.identifier(classState.node.id.name) : classState.scope.generateUidIdentifier("class"),
  452. superName: classState.node.superClass,
  453. isDerived: !!classState.node.superClass,
  454. constructorBody: _core.types.blockStatement([])
  455. });
  456. setState({
  457. extendsNative: _core.types.isIdentifier(classState.superName) && builtinClasses.has(classState.superName.name) && !classState.scope.hasBinding(classState.superName.name, true)
  458. });
  459. const {
  460. classRef,
  461. node,
  462. constructorBody
  463. } = classState;
  464. setState({
  465. construct: buildConstructor(classRef, constructorBody, node)
  466. });
  467. extractDynamicKeys();
  468. const {
  469. body
  470. } = classState;
  471. const {
  472. closureParams,
  473. closureArgs
  474. } = setupClosureParamsArgs();
  475. buildBody();
  476. if (!assumptions.noClassCalls) {
  477. constructorBody.body.unshift(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper("classCallCheck"), [_core.types.thisExpression(), _core.types.cloneNode(classState.classRef)])));
  478. }
  479. const isStrict = path.isInStrictMode();
  480. let constructorOnly = classState.classId && body.length === 1;
  481. if (constructorOnly && !isStrict) {
  482. for (const param of classState.construct.params) {
  483. if (!_core.types.isIdentifier(param)) {
  484. constructorOnly = false;
  485. break;
  486. }
  487. }
  488. }
  489. const directives = constructorOnly ? body[0].body.directives : [];
  490. if (!isStrict) {
  491. directives.push(_core.types.directive(_core.types.directiveLiteral("use strict")));
  492. }
  493. if (constructorOnly) {
  494. const expr = _core.types.toExpression(body[0]);
  495. return classState.isLoose ? expr : createClassHelper([expr]);
  496. }
  497. let returnArg = _core.types.cloneNode(classState.classRef);
  498. if (!classState.pushedCreateClass && !classState.isLoose) {
  499. returnArg = createClassHelper([returnArg]);
  500. }
  501. body.push(_core.types.returnStatement(returnArg));
  502. const container = _core.types.arrowFunctionExpression(closureParams, _core.types.blockStatement(body, directives));
  503. return _core.types.callExpression(container, closureArgs);
  504. }
  505. return classTransformer(path, file, builtinClasses, isLoose);
  506. }
  507. //# sourceMappingURL=transformClass.js.map