transformClass.js 20 KB

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