transformClass.js 20 KB

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