rewrite-live-references.js 9.4 KB

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