transformClass.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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. if (parentPath.isLoop() || parentPath.isConditional() || parentPath.isArrowFunctionExpression()) {
  261. maxGuaranteedSuperBeforeIndex = -1;
  262. return true;
  263. }
  264. lastParentPath = parentPath;
  265. });
  266. }
  267. }
  268. const guaranteedCalls = new Set();
  269. for (const thisPath of classState.superThises) {
  270. const {
  271. node,
  272. parentPath
  273. } = thisPath;
  274. if (parentPath.isMemberExpression({
  275. object: node
  276. })) {
  277. thisPath.replaceWith(thisRef());
  278. continue;
  279. }
  280. let thisIndex;
  281. thisPath.find(function (parentPath) {
  282. if (parentPath.parentPath === constructorBody) {
  283. thisIndex = parentPath.key;
  284. return true;
  285. }
  286. });
  287. let exprPath = thisPath.parentPath.isSequenceExpression() ? thisPath.parentPath : thisPath;
  288. if (exprPath.listKey === "arguments" && (exprPath.parentPath.isCallExpression() || exprPath.parentPath.isOptionalCallExpression())) {
  289. exprPath = exprPath.parentPath;
  290. } else {
  291. exprPath = null;
  292. }
  293. if (maxGuaranteedSuperBeforeIndex !== -1 && thisIndex > maxGuaranteedSuperBeforeIndex || guaranteedCalls.has(exprPath)) {
  294. thisPath.replaceWith(thisRef());
  295. } else {
  296. if (exprPath) {
  297. guaranteedCalls.add(exprPath);
  298. }
  299. thisPath.replaceWith(buildAssertThisInitialized());
  300. }
  301. }
  302. let wrapReturn;
  303. if (classState.isLoose) {
  304. wrapReturn = returnArg => {
  305. const thisExpr = buildAssertThisInitialized();
  306. return returnArg ? _core.types.logicalExpression("||", returnArg, thisExpr) : thisExpr;
  307. };
  308. } else {
  309. wrapReturn = returnArg => {
  310. const returnParams = [thisRef()];
  311. if (returnArg != null) {
  312. returnParams.push(returnArg);
  313. }
  314. return _core.types.callExpression(classState.file.addHelper("possibleConstructorReturn"), returnParams);
  315. };
  316. }
  317. const bodyPaths = body.get("body");
  318. const guaranteedSuperBeforeFinish = maxGuaranteedSuperBeforeIndex !== -1 && maxGuaranteedSuperBeforeIndex < bodyPaths.length;
  319. if (!bodyPaths.length || !bodyPaths.pop().isReturnStatement()) {
  320. body.pushContainer("body", _core.types.returnStatement(guaranteedSuperBeforeFinish ? thisRef() : buildAssertThisInitialized()));
  321. }
  322. for (const returnPath of classState.superReturns) {
  323. returnPath.get("argument").replaceWith(wrapReturn(returnPath.node.argument));
  324. }
  325. }
  326. function pushMethod(node, wrapped) {
  327. if (node.kind === "method") {
  328. if (processMethod(node)) return;
  329. }
  330. const placement = node.static ? "static" : "instance";
  331. const methods = classState.methods[placement];
  332. const descKey = node.kind === "method" ? "value" : node.kind;
  333. const key = _core.types.isNumericLiteral(node.key) || _core.types.isBigIntLiteral(node.key) ? _core.types.stringLiteral(String(node.key.value)) : _core.types.toComputedKey(node);
  334. methods.hasComputed = !_core.types.isStringLiteral(key);
  335. const fn = wrapped != null ? wrapped : _core.types.toExpression(node);
  336. let descriptor;
  337. if (!methods.hasComputed && methods.map.has(key.value)) {
  338. descriptor = methods.map.get(key.value);
  339. descriptor[descKey] = fn;
  340. if (descKey === "value") {
  341. descriptor.get = null;
  342. descriptor.set = null;
  343. } else {
  344. descriptor.value = null;
  345. }
  346. } else {
  347. descriptor = {
  348. key: key,
  349. [descKey]: fn
  350. };
  351. methods.list.push(descriptor);
  352. if (!methods.hasComputed) {
  353. methods.map.set(key.value, descriptor);
  354. }
  355. }
  356. }
  357. function processMethod(node) {
  358. if (assumptions.setClassMethods && !node.decorators) {
  359. let {
  360. classRef
  361. } = classState;
  362. if (!node.static) {
  363. insertProtoAliasOnce();
  364. classRef = classState.protoAlias;
  365. }
  366. const methodName = _core.types.memberExpression(_core.types.cloneNode(classRef), node.key, node.computed || _core.types.isLiteral(node.key));
  367. const func = _core.types.functionExpression(node.id, node.params, node.body, node.generator, node.async);
  368. _core.types.inherits(func, node);
  369. const expr = _core.types.expressionStatement(_core.types.assignmentExpression("=", methodName, func));
  370. _core.types.inheritsComments(expr, node);
  371. classState.body.push(expr);
  372. return true;
  373. }
  374. return false;
  375. }
  376. function insertProtoAliasOnce() {
  377. if (classState.protoAlias === null) {
  378. setState({
  379. protoAlias: classState.scope.generateUidIdentifier("proto")
  380. });
  381. const classProto = _core.types.memberExpression(classState.classRef, _core.types.identifier("prototype"));
  382. const protoDeclaration = _core.types.variableDeclaration("var", [_core.types.variableDeclarator(classState.protoAlias, classProto)]);
  383. classState.body.push(protoDeclaration);
  384. }
  385. }
  386. function pushConstructor(superReturns, method, path) {
  387. setState({
  388. userConstructorPath: path,
  389. userConstructor: method,
  390. hasConstructor: true,
  391. superReturns
  392. });
  393. const {
  394. construct
  395. } = classState;
  396. _core.types.inheritsComments(construct, method);
  397. construct.params = method.params;
  398. _core.types.inherits(construct.body, method.body);
  399. construct.body.directives = method.body.directives;
  400. if (classState.hasInstanceDescriptors || classState.hasStaticDescriptors) {
  401. pushDescriptors();
  402. }
  403. pushInheritsToBody();
  404. }
  405. function pushInheritsToBody() {
  406. if (!classState.isDerived || classState.pushedInherits) return;
  407. classState.pushedInherits = true;
  408. 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)])));
  409. }
  410. function extractDynamicKeys() {
  411. const {
  412. dynamicKeys,
  413. node,
  414. scope
  415. } = classState;
  416. for (const elem of node.body.body) {
  417. if (!_core.types.isClassMethod(elem) || !elem.computed) continue;
  418. if (scope.isPure(elem.key, true)) continue;
  419. const id = scope.generateUidIdentifierBasedOnNode(elem.key);
  420. dynamicKeys.set(id.name, elem.key);
  421. elem.key = id;
  422. }
  423. }
  424. function setupClosureParamsArgs() {
  425. const {
  426. superName,
  427. dynamicKeys
  428. } = classState;
  429. const closureParams = [];
  430. const closureArgs = [];
  431. if (classState.isDerived) {
  432. let arg = _core.types.cloneNode(superName);
  433. if (classState.extendsNative) {
  434. arg = _core.types.callExpression(classState.file.addHelper("wrapNativeSuper"), [arg]);
  435. (0, _helperAnnotateAsPure.default)(arg);
  436. }
  437. const param = classState.scope.generateUidIdentifierBasedOnNode(superName);
  438. closureParams.push(param);
  439. closureArgs.push(arg);
  440. setState({
  441. superName: _core.types.cloneNode(param)
  442. });
  443. }
  444. for (const [name, value] of dynamicKeys) {
  445. closureParams.push(_core.types.identifier(name));
  446. closureArgs.push(value);
  447. }
  448. return {
  449. closureParams,
  450. closureArgs
  451. };
  452. }
  453. function classTransformer(path, file, builtinClasses, isLoose) {
  454. setState({
  455. parent: path.parent,
  456. scope: path.scope,
  457. node: path.node,
  458. path,
  459. file,
  460. isLoose
  461. });
  462. setState({
  463. classId: classState.node.id,
  464. classRef: classState.node.id ? _core.types.identifier(classState.node.id.name) : classState.scope.generateUidIdentifier("class"),
  465. superName: classState.node.superClass,
  466. isDerived: !!classState.node.superClass,
  467. constructorBody: _core.types.blockStatement([])
  468. });
  469. setState({
  470. extendsNative: _core.types.isIdentifier(classState.superName) && builtinClasses.has(classState.superName.name) && !classState.scope.hasBinding(classState.superName.name, true)
  471. });
  472. const {
  473. classRef,
  474. node,
  475. constructorBody
  476. } = classState;
  477. setState({
  478. construct: buildConstructor(classRef, constructorBody, node)
  479. });
  480. extractDynamicKeys();
  481. const {
  482. body
  483. } = classState;
  484. const {
  485. closureParams,
  486. closureArgs
  487. } = setupClosureParamsArgs();
  488. buildBody();
  489. if (!assumptions.noClassCalls) {
  490. constructorBody.body.unshift(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper("classCallCheck"), [_core.types.thisExpression(), _core.types.cloneNode(classState.classRef)])));
  491. }
  492. const isStrict = path.isInStrictMode();
  493. let constructorOnly = body.length === 0;
  494. if (constructorOnly && !isStrict) {
  495. for (const param of classState.construct.params) {
  496. if (!_core.types.isIdentifier(param)) {
  497. constructorOnly = false;
  498. break;
  499. }
  500. }
  501. }
  502. const directives = constructorOnly ? classState.construct.body.directives : [];
  503. if (!isStrict) {
  504. directives.push(_core.types.directive(_core.types.directiveLiteral("use strict")));
  505. }
  506. if (constructorOnly) {
  507. const expr = _core.types.toExpression(classState.construct);
  508. return classState.isLoose ? expr : createClassHelper([expr]);
  509. }
  510. if (!classState.pushedCreateClass) {
  511. body.push(_core.types.returnStatement(classState.isLoose ? _core.types.cloneNode(classState.classRef) : createClassHelper([_core.types.cloneNode(classState.classRef)])));
  512. }
  513. body.unshift(classState.construct);
  514. const container = _core.types.arrowFunctionExpression(closureParams, _core.types.blockStatement(body, directives));
  515. return _core.types.callExpression(container, closureArgs);
  516. }
  517. return classTransformer(path, file, builtinClasses, isLoose);
  518. }
  519. //# sourceMappingURL=transformClass.js.map