rewrite-live-references.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = rewriteLiveReferences;
  6. var _assert = _interopRequireDefault(require("assert"));
  7. var t = _interopRequireWildcard(require("@babel/types"));
  8. var _template = _interopRequireDefault(require("@babel/template"));
  9. var _helperSimpleAccess = _interopRequireDefault(require("@babel/helper-simple-access"));
  10. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  11. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  12. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13. function rewriteLiveReferences(programPath, metadata) {
  14. const imported = new Map();
  15. const exported = new Map();
  16. const requeueInParent = path => {
  17. programPath.requeue(path);
  18. };
  19. for (const [source, data] of metadata.source) {
  20. for (const [localName, importName] of data.imports) {
  21. imported.set(localName, [source, importName, null]);
  22. }
  23. for (const localName of data.importsNamespace) {
  24. imported.set(localName, [source, null, localName]);
  25. }
  26. }
  27. for (const [local, data] of metadata.local) {
  28. let exportMeta = exported.get(local);
  29. if (!exportMeta) {
  30. exportMeta = [];
  31. exported.set(local, exportMeta);
  32. }
  33. exportMeta.push(...data.names);
  34. }
  35. programPath.traverse(rewriteBindingInitVisitor, {
  36. metadata,
  37. requeueInParent,
  38. scope: programPath.scope,
  39. exported
  40. });
  41. (0, _helperSimpleAccess.default)(programPath, new Set([...Array.from(imported.keys()), ...Array.from(exported.keys())]));
  42. programPath.traverse(rewriteReferencesVisitor, {
  43. seen: new WeakSet(),
  44. metadata,
  45. requeueInParent,
  46. scope: programPath.scope,
  47. imported,
  48. exported,
  49. buildImportReference: ([source, importName, localName], identNode) => {
  50. const meta = metadata.source.get(source);
  51. if (localName) {
  52. if (meta.lazy) identNode = t.callExpression(identNode, []);
  53. return identNode;
  54. }
  55. let namespace = t.identifier(meta.name);
  56. if (meta.lazy) namespace = t.callExpression(namespace, []);
  57. return t.memberExpression(namespace, t.identifier(importName));
  58. }
  59. });
  60. }
  61. const rewriteBindingInitVisitor = {
  62. Scope(path) {
  63. path.skip();
  64. },
  65. ClassDeclaration(path) {
  66. const {
  67. requeueInParent,
  68. exported,
  69. metadata
  70. } = this;
  71. const {
  72. id
  73. } = path.node;
  74. if (!id) throw new Error("Expected class to have a name");
  75. const localName = id.name;
  76. const exportNames = exported.get(localName) || [];
  77. if (exportNames.length > 0) {
  78. const statement = t.expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, t.identifier(localName)));
  79. statement._blockHoist = path.node._blockHoist;
  80. requeueInParent(path.insertAfter(statement)[0]);
  81. }
  82. },
  83. VariableDeclaration(path) {
  84. const {
  85. requeueInParent,
  86. exported,
  87. metadata
  88. } = this;
  89. Object.keys(path.getOuterBindingIdentifiers()).forEach(localName => {
  90. const exportNames = exported.get(localName) || [];
  91. if (exportNames.length > 0) {
  92. const statement = t.expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, t.identifier(localName)));
  93. statement._blockHoist = path.node._blockHoist;
  94. requeueInParent(path.insertAfter(statement)[0]);
  95. }
  96. });
  97. }
  98. };
  99. const buildBindingExportAssignmentExpression = (metadata, exportNames, localExpr) => {
  100. return (exportNames || []).reduce((expr, exportName) => {
  101. return t.assignmentExpression("=", t.memberExpression(t.identifier(metadata.exportName), t.identifier(exportName)), expr);
  102. }, localExpr);
  103. };
  104. const buildImportThrow = localName => {
  105. return _template.default.expression.ast`
  106. (function() {
  107. throw new Error('"' + '${localName}' + '" is read-only.');
  108. })()
  109. `;
  110. };
  111. const rewriteReferencesVisitor = {
  112. ReferencedIdentifier(path) {
  113. const {
  114. seen,
  115. buildImportReference,
  116. scope,
  117. imported,
  118. requeueInParent
  119. } = this;
  120. if (seen.has(path.node)) return;
  121. seen.add(path.node);
  122. const localName = path.node.name;
  123. const localBinding = path.scope.getBinding(localName);
  124. const rootBinding = scope.getBinding(localName);
  125. if (rootBinding !== localBinding) return;
  126. const importData = imported.get(localName);
  127. if (importData) {
  128. const ref = buildImportReference(importData, path.node);
  129. ref.loc = path.node.loc;
  130. if ((path.parentPath.isCallExpression({
  131. callee: path.node
  132. }) || path.parentPath.isOptionalCallExpression({
  133. callee: path.node
  134. }) || path.parentPath.isTaggedTemplateExpression({
  135. tag: path.node
  136. })) && t.isMemberExpression(ref)) {
  137. path.replaceWith(t.sequenceExpression([t.numericLiteral(0), ref]));
  138. } else if (path.isJSXIdentifier() && t.isMemberExpression(ref)) {
  139. const {
  140. object,
  141. property
  142. } = ref;
  143. path.replaceWith(t.JSXMemberExpression(t.JSXIdentifier(object.name), t.JSXIdentifier(property.name)));
  144. } else {
  145. path.replaceWith(ref);
  146. }
  147. requeueInParent(path);
  148. path.skip();
  149. }
  150. },
  151. AssignmentExpression: {
  152. exit(path) {
  153. const {
  154. scope,
  155. seen,
  156. imported,
  157. exported,
  158. requeueInParent,
  159. buildImportReference
  160. } = this;
  161. if (seen.has(path.node)) return;
  162. seen.add(path.node);
  163. const left = path.get("left");
  164. if (left.isMemberExpression()) return;
  165. if (left.isIdentifier()) {
  166. const localName = left.node.name;
  167. if (scope.getBinding(localName) !== path.scope.getBinding(localName)) {
  168. return;
  169. }
  170. const exportedNames = exported.get(localName);
  171. const importData = imported.get(localName);
  172. if ((exportedNames == null ? void 0 : exportedNames.length) > 0 || importData) {
  173. (0, _assert.default)(path.node.operator === "=", "Path was not simplified");
  174. const assignment = path.node;
  175. if (importData) {
  176. assignment.left = buildImportReference(importData, assignment.left);
  177. assignment.right = t.sequenceExpression([assignment.right, buildImportThrow(localName)]);
  178. }
  179. path.replaceWith(buildBindingExportAssignmentExpression(this.metadata, exportedNames, assignment));
  180. requeueInParent(path);
  181. }
  182. } else {
  183. const ids = left.getOuterBindingIdentifiers();
  184. const programScopeIds = Object.keys(ids).filter(localName => scope.getBinding(localName) === path.scope.getBinding(localName));
  185. const id = programScopeIds.find(localName => imported.has(localName));
  186. if (id) {
  187. path.node.right = t.sequenceExpression([path.node.right, buildImportThrow(id)]);
  188. }
  189. const items = [];
  190. programScopeIds.forEach(localName => {
  191. const exportedNames = exported.get(localName) || [];
  192. if (exportedNames.length > 0) {
  193. items.push(buildBindingExportAssignmentExpression(this.metadata, exportedNames, t.identifier(localName)));
  194. }
  195. });
  196. if (items.length > 0) {
  197. let node = t.sequenceExpression(items);
  198. if (path.parentPath.isExpressionStatement()) {
  199. node = t.expressionStatement(node);
  200. node._blockHoist = path.parentPath.node._blockHoist;
  201. }
  202. const statement = path.insertAfter(node)[0];
  203. requeueInParent(statement);
  204. }
  205. }
  206. }
  207. },
  208. "ForOfStatement|ForInStatement"(path) {
  209. const {
  210. scope,
  211. node
  212. } = path;
  213. const {
  214. left
  215. } = node;
  216. const {
  217. exported,
  218. scope: programScope
  219. } = this;
  220. if (!t.isVariableDeclaration(left)) {
  221. let didTransform = false;
  222. const bodyPath = path.get("body");
  223. const loopBodyScope = bodyPath.scope;
  224. for (const name of Object.keys(t.getOuterBindingIdentifiers(left))) {
  225. if (exported.get(name) && programScope.getBinding(name) === scope.getBinding(name)) {
  226. didTransform = true;
  227. if (loopBodyScope.hasOwnBinding(name)) {
  228. loopBodyScope.rename(name);
  229. }
  230. }
  231. }
  232. if (!didTransform) {
  233. return;
  234. }
  235. const newLoopId = scope.generateUidIdentifierBasedOnNode(left);
  236. bodyPath.unshiftContainer("body", t.expressionStatement(t.assignmentExpression("=", left, newLoopId)));
  237. path.get("left").replaceWith(t.variableDeclaration("let", [t.variableDeclarator(newLoopId)]));
  238. scope.registerDeclaration(path.get("left"));
  239. }
  240. }
  241. };