transformClass.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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 _helperOptimiseCallExpression = require("@babel/helper-optimise-call-expression");
  9. var _core = require("@babel/core");
  10. var _helperAnnotateAsPure = require("@babel/helper-annotate-as-pure");
  11. var _inlineCreateSuperHelpers = require("./inline-createSuper-helpers");
  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) {
  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. superFnId: undefined,
  27. superName: undefined,
  28. superReturns: [],
  29. isDerived: false,
  30. extendsNative: false,
  31. construct: undefined,
  32. constructorBody: undefined,
  33. userConstructor: undefined,
  34. userConstructorPath: undefined,
  35. hasConstructor: false,
  36. staticPropBody: [],
  37. body: [],
  38. superThises: [],
  39. pushedConstructor: false,
  40. pushedInherits: false,
  41. protoAlias: null,
  42. isLoose: false,
  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([_helperReplaceSupers.environmentVisitor, {
  60. ThisExpression(path) {
  61. classState.superThises.push(path);
  62. }
  63. }]);
  64. function maybeCreateConstructor() {
  65. let hasConstructor = false;
  66. const paths = classState.path.get("body.body");
  67. for (const path of paths) {
  68. hasConstructor = path.equals("kind", "constructor");
  69. if (hasConstructor) break;
  70. }
  71. if (hasConstructor) return;
  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. classState.path.get("body").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 = constructorBody.body.concat(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()) {
  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(_core.traverse.visitors.merge([_helperReplaceSupers.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. pushMethod(node, path);
  136. }
  137. }
  138. }
  139. }
  140. function pushDescriptors() {
  141. pushInheritsToBody();
  142. const {
  143. body
  144. } = classState;
  145. const props = {
  146. instance: null,
  147. static: null
  148. };
  149. for (const placement of ["static", "instance"]) {
  150. if (classState.methods[placement].list.length) {
  151. props[placement] = classState.methods[placement].list.map(desc => {
  152. const obj = _core.types.objectExpression([_core.types.objectProperty(_core.types.identifier("key"), desc.key)]);
  153. for (const kind of ["get", "set", "value"]) {
  154. if (desc[kind] != null) {
  155. obj.properties.push(_core.types.objectProperty(_core.types.identifier(kind), desc[kind]));
  156. }
  157. }
  158. return obj;
  159. });
  160. }
  161. }
  162. if (props.instance || props.static) {
  163. 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()];
  164. let lastNonNullIndex = 0;
  165. for (let i = 0; i < args.length; i++) {
  166. if (!_core.types.isNullLiteral(args[i])) lastNonNullIndex = i;
  167. }
  168. args = args.slice(0, lastNonNullIndex + 1);
  169. body.push(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper("createClass"), args)));
  170. }
  171. }
  172. function wrapSuperCall(bareSuper, superRef, thisRef, body) {
  173. const bareSuperNode = bareSuper.node;
  174. let call;
  175. if (assumptions.superIsCallableConstructor) {
  176. bareSuperNode.arguments.unshift(_core.types.thisExpression());
  177. if (bareSuperNode.arguments.length === 2 && _core.types.isSpreadElement(bareSuperNode.arguments[1]) && _core.types.isIdentifier(bareSuperNode.arguments[1].argument, {
  178. name: "arguments"
  179. })) {
  180. bareSuperNode.arguments[1] = bareSuperNode.arguments[1].argument;
  181. bareSuperNode.callee = _core.types.memberExpression(_core.types.cloneNode(superRef), _core.types.identifier("apply"));
  182. } else {
  183. bareSuperNode.callee = _core.types.memberExpression(_core.types.cloneNode(superRef), _core.types.identifier("call"));
  184. }
  185. call = _core.types.logicalExpression("||", bareSuperNode, _core.types.thisExpression());
  186. } else {
  187. call = (0, _helperOptimiseCallExpression.default)(_core.types.cloneNode(classState.superFnId), _core.types.thisExpression(), bareSuperNode.arguments, false);
  188. }
  189. if (bareSuper.parentPath.isExpressionStatement() && bareSuper.parentPath.container === body.node.body && body.node.body.length - 1 === bareSuper.parentPath.key) {
  190. if (classState.superThises.length) {
  191. call = _core.types.assignmentExpression("=", thisRef(), call);
  192. }
  193. bareSuper.parentPath.replaceWith(_core.types.returnStatement(call));
  194. } else {
  195. bareSuper.replaceWith(_core.types.assignmentExpression("=", thisRef(), call));
  196. }
  197. }
  198. function verifyConstructor() {
  199. if (!classState.isDerived) return;
  200. const path = classState.userConstructorPath;
  201. const body = path.get("body");
  202. path.traverse(findThisesVisitor);
  203. let thisRef = function () {
  204. const ref = path.scope.generateDeclaredUidIdentifier("this");
  205. thisRef = () => _core.types.cloneNode(ref);
  206. return ref;
  207. };
  208. for (const thisPath of classState.superThises) {
  209. const {
  210. node,
  211. parentPath
  212. } = thisPath;
  213. if (parentPath.isMemberExpression({
  214. object: node
  215. })) {
  216. thisPath.replaceWith(thisRef());
  217. continue;
  218. }
  219. thisPath.replaceWith(_core.types.callExpression(classState.file.addHelper("assertThisInitialized"), [thisRef()]));
  220. }
  221. const bareSupers = new Set();
  222. path.traverse(_core.traverse.visitors.merge([_helperReplaceSupers.environmentVisitor, {
  223. Super(path) {
  224. const {
  225. node,
  226. parentPath
  227. } = path;
  228. if (parentPath.isCallExpression({
  229. callee: node
  230. })) {
  231. bareSupers.add(parentPath);
  232. }
  233. }
  234. }]));
  235. let guaranteedSuperBeforeFinish = !!bareSupers.size;
  236. for (const bareSuper of bareSupers) {
  237. wrapSuperCall(bareSuper, classState.superName, thisRef, body);
  238. if (guaranteedSuperBeforeFinish) {
  239. bareSuper.find(function (parentPath) {
  240. if (parentPath === path) {
  241. return true;
  242. }
  243. if (parentPath.isLoop() || parentPath.isConditional() || parentPath.isArrowFunctionExpression()) {
  244. guaranteedSuperBeforeFinish = false;
  245. return true;
  246. }
  247. });
  248. }
  249. }
  250. let wrapReturn;
  251. if (classState.isLoose) {
  252. wrapReturn = returnArg => {
  253. const thisExpr = _core.types.callExpression(classState.file.addHelper("assertThisInitialized"), [thisRef()]);
  254. return returnArg ? _core.types.logicalExpression("||", returnArg, thisExpr) : thisExpr;
  255. };
  256. } else {
  257. wrapReturn = returnArg => _core.types.callExpression(classState.file.addHelper("possibleConstructorReturn"), [thisRef()].concat(returnArg || []));
  258. }
  259. const bodyPaths = body.get("body");
  260. if (!bodyPaths.length || !bodyPaths.pop().isReturnStatement()) {
  261. body.pushContainer("body", _core.types.returnStatement(guaranteedSuperBeforeFinish ? thisRef() : wrapReturn()));
  262. }
  263. for (const returnPath of classState.superReturns) {
  264. returnPath.get("argument").replaceWith(wrapReturn(returnPath.node.argument));
  265. }
  266. }
  267. function pushMethod(node, path) {
  268. const scope = path ? path.scope : classState.scope;
  269. if (node.kind === "method") {
  270. if (processMethod(node, scope)) return;
  271. }
  272. const placement = node.static ? "static" : "instance";
  273. const methods = classState.methods[placement];
  274. const descKey = node.kind === "method" ? "value" : node.kind;
  275. const key = _core.types.isNumericLiteral(node.key) || _core.types.isBigIntLiteral(node.key) ? _core.types.stringLiteral(String(node.key.value)) : _core.types.toComputedKey(node);
  276. let fn = _core.types.toExpression(node);
  277. if (_core.types.isStringLiteral(key)) {
  278. if (node.kind === "method") {
  279. fn = (0, _helperFunctionName.default)({
  280. id: key,
  281. node: node,
  282. scope
  283. });
  284. }
  285. } else {
  286. methods.hasComputed = true;
  287. }
  288. let descriptor;
  289. if (!methods.hasComputed && methods.map.has(key.value)) {
  290. descriptor = methods.map.get(key.value);
  291. descriptor[descKey] = fn;
  292. if (descKey === "value") {
  293. descriptor.get = null;
  294. descriptor.set = null;
  295. } else {
  296. descriptor.value = null;
  297. }
  298. } else {
  299. descriptor = {
  300. key: key,
  301. [descKey]: fn
  302. };
  303. methods.list.push(descriptor);
  304. if (!methods.hasComputed) {
  305. methods.map.set(key.value, descriptor);
  306. }
  307. }
  308. }
  309. function processMethod(node, scope) {
  310. if (assumptions.setClassMethods && !node.decorators) {
  311. let {
  312. classRef
  313. } = classState;
  314. if (!node.static) {
  315. insertProtoAliasOnce();
  316. classRef = classState.protoAlias;
  317. }
  318. const methodName = _core.types.memberExpression(_core.types.cloneNode(classRef), node.key, node.computed || _core.types.isLiteral(node.key));
  319. let func = _core.types.functionExpression(null, node.params, node.body, node.generator, node.async);
  320. _core.types.inherits(func, node);
  321. const key = _core.types.toComputedKey(node, node.key);
  322. if (_core.types.isStringLiteral(key)) {
  323. func = (0, _helperFunctionName.default)({
  324. node: func,
  325. id: key,
  326. scope
  327. });
  328. }
  329. const expr = _core.types.expressionStatement(_core.types.assignmentExpression("=", methodName, func));
  330. _core.types.inheritsComments(expr, node);
  331. classState.body.push(expr);
  332. return true;
  333. }
  334. return false;
  335. }
  336. function insertProtoAliasOnce() {
  337. if (classState.protoAlias === null) {
  338. setState({
  339. protoAlias: classState.scope.generateUidIdentifier("proto")
  340. });
  341. const classProto = _core.types.memberExpression(classState.classRef, _core.types.identifier("prototype"));
  342. const protoDeclaration = _core.types.variableDeclaration("var", [_core.types.variableDeclarator(classState.protoAlias, classProto)]);
  343. classState.body.push(protoDeclaration);
  344. }
  345. }
  346. function pushConstructor(superReturns, method, path) {
  347. setState({
  348. userConstructorPath: path,
  349. userConstructor: method,
  350. hasConstructor: true,
  351. superReturns
  352. });
  353. const {
  354. construct
  355. } = classState;
  356. _core.types.inheritsComments(construct, method);
  357. construct.params = method.params;
  358. _core.types.inherits(construct.body, method.body);
  359. construct.body.directives = method.body.directives;
  360. pushConstructorToBody();
  361. }
  362. function pushConstructorToBody() {
  363. if (classState.pushedConstructor) return;
  364. classState.pushedConstructor = true;
  365. if (classState.hasInstanceDescriptors || classState.hasStaticDescriptors) {
  366. pushDescriptors();
  367. }
  368. classState.body.push(classState.construct);
  369. pushInheritsToBody();
  370. }
  371. function pushInheritsToBody() {
  372. if (!classState.isDerived || classState.pushedInherits) return;
  373. const superFnId = path.scope.generateUidIdentifier("super");
  374. setState({
  375. pushedInherits: true,
  376. superFnId
  377. });
  378. if (!assumptions.superIsCallableConstructor) {
  379. classState.body.unshift(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(superFnId, _core.types.callExpression((0, _inlineCreateSuperHelpers.default)(classState.file), [_core.types.cloneNode(classState.classRef)]))]));
  380. }
  381. 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)])));
  382. }
  383. function setupClosureParamsArgs() {
  384. const {
  385. superName
  386. } = classState;
  387. const closureParams = [];
  388. const closureArgs = [];
  389. if (classState.isDerived) {
  390. let arg = _core.types.cloneNode(superName);
  391. if (classState.extendsNative) {
  392. arg = _core.types.callExpression(classState.file.addHelper("wrapNativeSuper"), [arg]);
  393. (0, _helperAnnotateAsPure.default)(arg);
  394. }
  395. const param = classState.scope.generateUidIdentifierBasedOnNode(superName);
  396. closureParams.push(param);
  397. closureArgs.push(arg);
  398. setState({
  399. superName: _core.types.cloneNode(param)
  400. });
  401. }
  402. return {
  403. closureParams,
  404. closureArgs
  405. };
  406. }
  407. function classTransformer(path, file, builtinClasses, isLoose) {
  408. setState({
  409. parent: path.parent,
  410. scope: path.scope,
  411. node: path.node,
  412. path,
  413. file,
  414. isLoose
  415. });
  416. setState({
  417. classId: classState.node.id,
  418. classRef: classState.node.id ? _core.types.identifier(classState.node.id.name) : classState.scope.generateUidIdentifier("class"),
  419. superName: classState.node.superClass,
  420. isDerived: !!classState.node.superClass,
  421. constructorBody: _core.types.blockStatement([])
  422. });
  423. setState({
  424. extendsNative: classState.isDerived && builtinClasses.has(classState.superName.name) && !classState.scope.hasBinding(classState.superName.name, true)
  425. });
  426. const {
  427. classRef,
  428. node,
  429. constructorBody
  430. } = classState;
  431. setState({
  432. construct: buildConstructor(classRef, constructorBody, node)
  433. });
  434. let {
  435. body
  436. } = classState;
  437. const {
  438. closureParams,
  439. closureArgs
  440. } = setupClosureParamsArgs();
  441. buildBody();
  442. if (!assumptions.noClassCalls) {
  443. constructorBody.body.unshift(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper("classCallCheck"), [_core.types.thisExpression(), _core.types.cloneNode(classState.classRef)])));
  444. }
  445. body = body.concat(classState.staticPropBody.map(fn => fn(_core.types.cloneNode(classState.classRef))));
  446. const isStrict = path.isInStrictMode();
  447. let constructorOnly = classState.classId && body.length === 1;
  448. if (constructorOnly && !isStrict) {
  449. for (const param of classState.construct.params) {
  450. if (!_core.types.isIdentifier(param)) {
  451. constructorOnly = false;
  452. break;
  453. }
  454. }
  455. }
  456. const directives = constructorOnly ? body[0].body.directives : [];
  457. if (!isStrict) {
  458. directives.push(_core.types.directive(_core.types.directiveLiteral("use strict")));
  459. }
  460. if (constructorOnly) {
  461. return _core.types.toExpression(body[0]);
  462. }
  463. body.push(_core.types.returnStatement(_core.types.cloneNode(classState.classRef)));
  464. const container = _core.types.arrowFunctionExpression(closureParams, _core.types.blockStatement(body, directives));
  465. return _core.types.callExpression(container, closureArgs);
  466. }
  467. return classTransformer(path, file, builtinClasses, isLoose);
  468. }