transformClass.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = transformClass;
  6. function _helperFunctionName() {
  7. const data = _interopRequireDefault(require("@babel/helper-function-name"));
  8. _helperFunctionName = function () {
  9. return data;
  10. };
  11. return data;
  12. }
  13. function _helperReplaceSupers() {
  14. const data = _interopRequireWildcard(require("@babel/helper-replace-supers"));
  15. _helperReplaceSupers = function () {
  16. return data;
  17. };
  18. return data;
  19. }
  20. function _helperOptimiseCallExpression() {
  21. const data = _interopRequireDefault(require("@babel/helper-optimise-call-expression"));
  22. _helperOptimiseCallExpression = function () {
  23. return data;
  24. };
  25. return data;
  26. }
  27. function defineMap() {
  28. const data = _interopRequireWildcard(require("@babel/helper-define-map"));
  29. defineMap = function () {
  30. return data;
  31. };
  32. return data;
  33. }
  34. function _core() {
  35. const data = require("@babel/core");
  36. _core = function () {
  37. return data;
  38. };
  39. return data;
  40. }
  41. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
  42. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  43. function buildConstructor(classRef, constructorBody, node) {
  44. const func = _core().types.functionDeclaration(_core().types.cloneNode(classRef), [], constructorBody);
  45. _core().types.inherits(func, node);
  46. return func;
  47. }
  48. function transformClass(path, file, builtinClasses, isLoose) {
  49. const classState = {
  50. parent: undefined,
  51. scope: undefined,
  52. node: undefined,
  53. path: undefined,
  54. file: undefined,
  55. classId: undefined,
  56. classRef: undefined,
  57. superName: undefined,
  58. superReturns: [],
  59. isDerived: false,
  60. extendsNative: false,
  61. construct: undefined,
  62. constructorBody: undefined,
  63. userConstructor: undefined,
  64. userConstructorPath: undefined,
  65. hasConstructor: false,
  66. instancePropBody: [],
  67. instancePropRefs: {},
  68. staticPropBody: [],
  69. body: [],
  70. superThises: [],
  71. pushedConstructor: false,
  72. pushedInherits: false,
  73. protoAlias: null,
  74. isLoose: false,
  75. hasInstanceDescriptors: false,
  76. hasStaticDescriptors: false,
  77. instanceMutatorMap: {},
  78. staticMutatorMap: {}
  79. };
  80. const setState = newState => {
  81. Object.assign(classState, newState);
  82. };
  83. const findThisesVisitor = _core().traverse.visitors.merge([_helperReplaceSupers().environmentVisitor, {
  84. ThisExpression(path) {
  85. classState.superThises.push(path);
  86. }
  87. }]);
  88. function pushToMap(node, enumerable, kind = "value", scope) {
  89. let mutatorMap;
  90. if (node.static) {
  91. setState({
  92. hasStaticDescriptors: true
  93. });
  94. mutatorMap = classState.staticMutatorMap;
  95. } else {
  96. setState({
  97. hasInstanceDescriptors: true
  98. });
  99. mutatorMap = classState.instanceMutatorMap;
  100. }
  101. const map = defineMap().push(mutatorMap, node, kind, classState.file, scope);
  102. if (enumerable) {
  103. map.enumerable = _core().types.booleanLiteral(true);
  104. }
  105. return map;
  106. }
  107. function maybeCreateConstructor() {
  108. let hasConstructor = false;
  109. const paths = classState.path.get("body.body");
  110. for (const path of paths) {
  111. hasConstructor = path.equals("kind", "constructor");
  112. if (hasConstructor) break;
  113. }
  114. if (hasConstructor) return;
  115. let params, body;
  116. if (classState.isDerived) {
  117. const constructor = _core().template.expression.ast`
  118. (function () {
  119. super(...arguments);
  120. })
  121. `;
  122. params = constructor.params;
  123. body = constructor.body;
  124. } else {
  125. params = [];
  126. body = _core().types.blockStatement([]);
  127. }
  128. classState.path.get("body").unshiftContainer("body", _core().types.classMethod("constructor", _core().types.identifier("constructor"), params, body));
  129. }
  130. function buildBody() {
  131. maybeCreateConstructor();
  132. pushBody();
  133. verifyConstructor();
  134. if (classState.userConstructor) {
  135. const {
  136. constructorBody,
  137. userConstructor,
  138. construct
  139. } = classState;
  140. constructorBody.body = constructorBody.body.concat(userConstructor.body.body);
  141. _core().types.inherits(construct, userConstructor);
  142. _core().types.inherits(constructorBody, userConstructor.body);
  143. }
  144. pushDescriptors();
  145. }
  146. function pushBody() {
  147. const classBodyPaths = classState.path.get("body.body");
  148. for (const path of classBodyPaths) {
  149. const node = path.node;
  150. if (path.isClassProperty()) {
  151. throw path.buildCodeFrameError("Missing class properties transform.");
  152. }
  153. if (node.decorators) {
  154. throw path.buildCodeFrameError("Method has decorators, put the decorator plugin before the classes one.");
  155. }
  156. if (_core().types.isClassMethod(node)) {
  157. const isConstructor = node.kind === "constructor";
  158. const replaceSupers = new (_helperReplaceSupers().default)({
  159. methodPath: path,
  160. objectRef: classState.classRef,
  161. superRef: classState.superName,
  162. isLoose: classState.isLoose,
  163. file: classState.file
  164. });
  165. replaceSupers.replace();
  166. const superReturns = [];
  167. path.traverse(_core().traverse.visitors.merge([_helperReplaceSupers().environmentVisitor, {
  168. ReturnStatement(path) {
  169. if (!path.getFunctionParent().isArrowFunctionExpression()) {
  170. superReturns.push(path);
  171. }
  172. }
  173. }]));
  174. if (isConstructor) {
  175. pushConstructor(superReturns, node, path);
  176. } else {
  177. pushMethod(node, path);
  178. }
  179. }
  180. }
  181. }
  182. function clearDescriptors() {
  183. setState({
  184. hasInstanceDescriptors: false,
  185. hasStaticDescriptors: false,
  186. instanceMutatorMap: {},
  187. staticMutatorMap: {}
  188. });
  189. }
  190. function pushDescriptors() {
  191. pushInheritsToBody();
  192. const {
  193. body
  194. } = classState;
  195. let instanceProps;
  196. let staticProps;
  197. if (classState.hasInstanceDescriptors) {
  198. instanceProps = defineMap().toClassObject(classState.instanceMutatorMap);
  199. }
  200. if (classState.hasStaticDescriptors) {
  201. staticProps = defineMap().toClassObject(classState.staticMutatorMap);
  202. }
  203. if (instanceProps || staticProps) {
  204. if (instanceProps) {
  205. instanceProps = defineMap().toComputedObjectFromClass(instanceProps);
  206. }
  207. if (staticProps) {
  208. staticProps = defineMap().toComputedObjectFromClass(staticProps);
  209. }
  210. let args = [_core().types.cloneNode(classState.classRef), _core().types.nullLiteral(), _core().types.nullLiteral()];
  211. if (instanceProps) args[1] = instanceProps;
  212. if (staticProps) args[2] = staticProps;
  213. let lastNonNullIndex = 0;
  214. for (let i = 0; i < args.length; i++) {
  215. if (!_core().types.isNullLiteral(args[i])) lastNonNullIndex = i;
  216. }
  217. args = args.slice(0, lastNonNullIndex + 1);
  218. body.push(_core().types.expressionStatement(_core().types.callExpression(classState.file.addHelper("createClass"), args)));
  219. }
  220. clearDescriptors();
  221. }
  222. function wrapSuperCall(bareSuper, superRef, thisRef, body) {
  223. let bareSuperNode = bareSuper.node;
  224. let call;
  225. if (classState.isLoose) {
  226. bareSuperNode.arguments.unshift(_core().types.thisExpression());
  227. if (bareSuperNode.arguments.length === 2 && _core().types.isSpreadElement(bareSuperNode.arguments[1]) && _core().types.isIdentifier(bareSuperNode.arguments[1].argument, {
  228. name: "arguments"
  229. })) {
  230. bareSuperNode.arguments[1] = bareSuperNode.arguments[1].argument;
  231. bareSuperNode.callee = _core().types.memberExpression(_core().types.cloneNode(superRef), _core().types.identifier("apply"));
  232. } else {
  233. bareSuperNode.callee = _core().types.memberExpression(_core().types.cloneNode(superRef), _core().types.identifier("call"));
  234. }
  235. call = _core().types.logicalExpression("||", bareSuperNode, _core().types.thisExpression());
  236. } else {
  237. bareSuperNode = (0, _helperOptimiseCallExpression().default)(_core().types.callExpression(classState.file.addHelper("getPrototypeOf"), [_core().types.cloneNode(classState.classRef)]), _core().types.thisExpression(), bareSuperNode.arguments);
  238. call = _core().types.callExpression(classState.file.addHelper("possibleConstructorReturn"), [_core().types.thisExpression(), bareSuperNode]);
  239. }
  240. if (bareSuper.parentPath.isExpressionStatement() && bareSuper.parentPath.container === body.node.body && body.node.body.length - 1 === bareSuper.parentPath.key) {
  241. if (classState.superThises.length) {
  242. call = _core().types.assignmentExpression("=", thisRef(), call);
  243. }
  244. bareSuper.parentPath.replaceWith(_core().types.returnStatement(call));
  245. } else {
  246. bareSuper.replaceWith(_core().types.assignmentExpression("=", thisRef(), call));
  247. }
  248. }
  249. function verifyConstructor() {
  250. if (!classState.isDerived) return;
  251. const path = classState.userConstructorPath;
  252. const body = path.get("body");
  253. path.traverse(findThisesVisitor);
  254. let thisRef = function () {
  255. const ref = path.scope.generateDeclaredUidIdentifier("this");
  256. thisRef = () => _core().types.cloneNode(ref);
  257. return ref;
  258. };
  259. for (const thisPath of classState.superThises) {
  260. const {
  261. node,
  262. parentPath
  263. } = thisPath;
  264. if (parentPath.isMemberExpression({
  265. object: node
  266. })) {
  267. thisPath.replaceWith(thisRef());
  268. continue;
  269. }
  270. thisPath.replaceWith(_core().types.callExpression(classState.file.addHelper("assertThisInitialized"), [thisRef()]));
  271. }
  272. const bareSupers = new Set();
  273. path.traverse(_core().traverse.visitors.merge([_helperReplaceSupers().environmentVisitor, {
  274. Super(path) {
  275. const {
  276. node,
  277. parentPath
  278. } = path;
  279. if (parentPath.isCallExpression({
  280. callee: node
  281. })) {
  282. bareSupers.add(parentPath);
  283. }
  284. }
  285. }]));
  286. let guaranteedSuperBeforeFinish = !!bareSupers.size;
  287. for (const bareSuper of bareSupers) {
  288. wrapSuperCall(bareSuper, classState.superName, thisRef, body);
  289. if (guaranteedSuperBeforeFinish) {
  290. bareSuper.find(function (parentPath) {
  291. if (parentPath === path) {
  292. return true;
  293. }
  294. if (parentPath.isLoop() || parentPath.isConditional() || parentPath.isArrowFunctionExpression()) {
  295. guaranteedSuperBeforeFinish = false;
  296. return true;
  297. }
  298. });
  299. }
  300. }
  301. let wrapReturn;
  302. if (classState.isLoose) {
  303. wrapReturn = returnArg => {
  304. const thisExpr = _core().types.callExpression(classState.file.addHelper("assertThisInitialized"), [thisRef()]);
  305. return returnArg ? _core().types.logicalExpression("||", returnArg, thisExpr) : thisExpr;
  306. };
  307. } else {
  308. wrapReturn = returnArg => _core().types.callExpression(classState.file.addHelper("possibleConstructorReturn"), [thisRef()].concat(returnArg || []));
  309. }
  310. const bodyPaths = body.get("body");
  311. if (!bodyPaths.length || !bodyPaths.pop().isReturnStatement()) {
  312. body.pushContainer("body", _core().types.returnStatement(guaranteedSuperBeforeFinish ? thisRef() : wrapReturn()));
  313. }
  314. for (const returnPath of classState.superReturns) {
  315. returnPath.get("argument").replaceWith(wrapReturn(returnPath.node.argument));
  316. }
  317. }
  318. function pushMethod(node, path) {
  319. const scope = path ? path.scope : classState.scope;
  320. if (node.kind === "method") {
  321. if (processMethod(node, scope)) return;
  322. }
  323. pushToMap(node, false, null, scope);
  324. }
  325. function processMethod(node, scope) {
  326. if (classState.isLoose && !node.decorators) {
  327. let {
  328. classRef
  329. } = classState;
  330. if (!node.static) {
  331. insertProtoAliasOnce();
  332. classRef = classState.protoAlias;
  333. }
  334. const methodName = _core().types.memberExpression(_core().types.cloneNode(classRef), node.key, node.computed || _core().types.isLiteral(node.key));
  335. let func = _core().types.functionExpression(null, node.params, node.body, node.generator, node.async);
  336. _core().types.inherits(func, node);
  337. const key = _core().types.toComputedKey(node, node.key);
  338. if (_core().types.isStringLiteral(key)) {
  339. func = (0, _helperFunctionName().default)({
  340. node: func,
  341. id: key,
  342. scope
  343. });
  344. }
  345. const expr = _core().types.expressionStatement(_core().types.assignmentExpression("=", methodName, func));
  346. _core().types.inheritsComments(expr, node);
  347. classState.body.push(expr);
  348. return true;
  349. }
  350. return false;
  351. }
  352. function insertProtoAliasOnce() {
  353. if (classState.protoAlias === null) {
  354. setState({
  355. protoAlias: classState.scope.generateUidIdentifier("proto")
  356. });
  357. const classProto = _core().types.memberExpression(classState.classRef, _core().types.identifier("prototype"));
  358. const protoDeclaration = _core().types.variableDeclaration("var", [_core().types.variableDeclarator(classState.protoAlias, classProto)]);
  359. classState.body.push(protoDeclaration);
  360. }
  361. }
  362. function pushConstructor(superReturns, method, path) {
  363. if (path.scope.hasOwnBinding(classState.classRef.name)) {
  364. path.scope.rename(classState.classRef.name);
  365. }
  366. setState({
  367. userConstructorPath: path,
  368. userConstructor: method,
  369. hasConstructor: true,
  370. superReturns
  371. });
  372. const {
  373. construct
  374. } = classState;
  375. _core().types.inheritsComments(construct, method);
  376. construct.params = method.params;
  377. _core().types.inherits(construct.body, method.body);
  378. construct.body.directives = method.body.directives;
  379. pushConstructorToBody();
  380. }
  381. function pushConstructorToBody() {
  382. if (classState.pushedConstructor) return;
  383. classState.pushedConstructor = true;
  384. if (classState.hasInstanceDescriptors || classState.hasStaticDescriptors) {
  385. pushDescriptors();
  386. }
  387. classState.body.push(classState.construct);
  388. pushInheritsToBody();
  389. }
  390. function pushInheritsToBody() {
  391. if (!classState.isDerived || classState.pushedInherits) return;
  392. setState({
  393. pushedInherits: true
  394. });
  395. 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)])));
  396. }
  397. function setupClosureParamsArgs() {
  398. const {
  399. superName
  400. } = classState;
  401. const closureParams = [];
  402. const closureArgs = [];
  403. if (classState.isDerived) {
  404. const arg = classState.extendsNative ? _core().types.callExpression(classState.file.addHelper("wrapNativeSuper"), [_core().types.cloneNode(superName)]) : _core().types.cloneNode(superName);
  405. const param = classState.scope.generateUidIdentifierBasedOnNode(superName);
  406. closureParams.push(param);
  407. closureArgs.push(arg);
  408. setState({
  409. superName: _core().types.cloneNode(param)
  410. });
  411. }
  412. return {
  413. closureParams,
  414. closureArgs
  415. };
  416. }
  417. function classTransformer(path, file, builtinClasses, isLoose) {
  418. setState({
  419. parent: path.parent,
  420. scope: path.scope,
  421. node: path.node,
  422. path,
  423. file,
  424. isLoose
  425. });
  426. setState({
  427. classId: classState.node.id,
  428. classRef: classState.node.id ? _core().types.identifier(classState.node.id.name) : classState.scope.generateUidIdentifier("class"),
  429. superName: classState.node.superClass,
  430. isDerived: !!classState.node.superClass,
  431. constructorBody: _core().types.blockStatement([])
  432. });
  433. setState({
  434. extendsNative: classState.isDerived && builtinClasses.has(classState.superName.name) && !classState.scope.hasBinding(classState.superName.name, true)
  435. });
  436. const {
  437. classRef,
  438. node,
  439. constructorBody
  440. } = classState;
  441. setState({
  442. construct: buildConstructor(classRef, constructorBody, node)
  443. });
  444. let {
  445. body
  446. } = classState;
  447. const {
  448. closureParams,
  449. closureArgs
  450. } = setupClosureParamsArgs();
  451. buildBody();
  452. if (!classState.isLoose) {
  453. constructorBody.body.unshift(_core().types.expressionStatement(_core().types.callExpression(classState.file.addHelper("classCallCheck"), [_core().types.thisExpression(), _core().types.cloneNode(classState.classRef)])));
  454. }
  455. body = body.concat(classState.staticPropBody.map(fn => fn(_core().types.cloneNode(classState.classRef))));
  456. const isStrict = path.isInStrictMode();
  457. let constructorOnly = classState.classId && body.length === 1;
  458. if (constructorOnly && !isStrict) {
  459. for (const param of classState.construct.params) {
  460. if (!_core().types.isIdentifier(param)) {
  461. constructorOnly = false;
  462. break;
  463. }
  464. }
  465. }
  466. const directives = constructorOnly ? body[0].body.directives : [];
  467. if (!isStrict) {
  468. directives.push(_core().types.directive(_core().types.directiveLiteral("use strict")));
  469. }
  470. if (constructorOnly) {
  471. return _core().types.toExpression(body[0]);
  472. }
  473. body.push(_core().types.returnStatement(_core().types.cloneNode(classState.classRef)));
  474. const container = _core().types.arrowFunctionExpression(closureParams, _core().types.blockStatement(body, directives));
  475. return _core().types.callExpression(container, closureArgs);
  476. }
  477. return classTransformer(path, file, builtinClasses, isLoose);
  478. }