transformClass.js 20 KB

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