transformClass.js 18 KB

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