rewrite-live-references.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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 isInType(path) {
  29. do {
  30. switch (path.parent.type) {
  31. case "TSTypeAnnotation":
  32. case "TSTypeAliasDeclaration":
  33. case "TSTypeReference":
  34. case "TypeAnnotation":
  35. case "TypeAlias":
  36. return true;
  37. case "ExportSpecifier":
  38. return path.parentPath.parent.exportKind === "type";
  39. default:
  40. if (path.parentPath.isStatement() || path.parentPath.isExpression()) {
  41. return false;
  42. }
  43. }
  44. } while (path = path.parentPath);
  45. }
  46. function rewriteLiveReferences(programPath, metadata) {
  47. const imported = new Map();
  48. const exported = new Map();
  49. const requeueInParent = path => {
  50. programPath.requeue(path);
  51. };
  52. for (const [source, data] of metadata.source) {
  53. for (const [localName, importName] of data.imports) {
  54. imported.set(localName, [source, importName, null]);
  55. }
  56. for (const localName of data.importsNamespace) {
  57. imported.set(localName, [source, null, localName]);
  58. }
  59. }
  60. for (const [local, data] of metadata.local) {
  61. let exportMeta = exported.get(local);
  62. if (!exportMeta) {
  63. exportMeta = [];
  64. exported.set(local, exportMeta);
  65. }
  66. exportMeta.push(...data.names);
  67. }
  68. const rewriteBindingInitVisitorState = {
  69. metadata,
  70. requeueInParent,
  71. scope: programPath.scope,
  72. exported
  73. };
  74. programPath.traverse(rewriteBindingInitVisitor, rewriteBindingInitVisitorState);
  75. (0, _helperSimpleAccess.default)(programPath, new Set([...Array.from(imported.keys()), ...Array.from(exported.keys())]), false);
  76. const rewriteReferencesVisitorState = {
  77. seen: new WeakSet(),
  78. metadata,
  79. requeueInParent,
  80. scope: programPath.scope,
  81. imported,
  82. exported,
  83. buildImportReference: ([source, importName, localName], identNode) => {
  84. const meta = metadata.source.get(source);
  85. if (localName) {
  86. if (meta.lazy) identNode = callExpression(identNode, []);
  87. return identNode;
  88. }
  89. let namespace = identifier(meta.name);
  90. if (meta.lazy) namespace = callExpression(namespace, []);
  91. if (importName === "default" && meta.interop === "node-default") {
  92. return namespace;
  93. }
  94. const computed = metadata.stringSpecifiers.has(importName);
  95. return memberExpression(namespace, computed ? stringLiteral(importName) : identifier(importName), computed);
  96. }
  97. };
  98. programPath.traverse(rewriteReferencesVisitor, rewriteReferencesVisitorState);
  99. }
  100. const rewriteBindingInitVisitor = {
  101. Scope(path) {
  102. path.skip();
  103. },
  104. ClassDeclaration(path) {
  105. const {
  106. requeueInParent,
  107. exported,
  108. metadata
  109. } = this;
  110. const {
  111. id
  112. } = path.node;
  113. if (!id) throw new Error("Expected class to have a name");
  114. const localName = id.name;
  115. const exportNames = exported.get(localName) || [];
  116. if (exportNames.length > 0) {
  117. const statement = expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, identifier(localName)));
  118. statement._blockHoist = path.node._blockHoist;
  119. requeueInParent(path.insertAfter(statement)[0]);
  120. }
  121. },
  122. VariableDeclaration(path) {
  123. const {
  124. requeueInParent,
  125. exported,
  126. metadata
  127. } = this;
  128. Object.keys(path.getOuterBindingIdentifiers()).forEach(localName => {
  129. const exportNames = exported.get(localName) || [];
  130. if (exportNames.length > 0) {
  131. const statement = expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, identifier(localName)));
  132. statement._blockHoist = path.node._blockHoist;
  133. requeueInParent(path.insertAfter(statement)[0]);
  134. }
  135. });
  136. }
  137. };
  138. const buildBindingExportAssignmentExpression = (metadata, exportNames, localExpr) => {
  139. return (exportNames || []).reduce((expr, exportName) => {
  140. const {
  141. stringSpecifiers
  142. } = metadata;
  143. const computed = stringSpecifiers.has(exportName);
  144. return assignmentExpression("=", memberExpression(identifier(metadata.exportName), computed ? stringLiteral(exportName) : identifier(exportName), computed), expr);
  145. }, localExpr);
  146. };
  147. const buildImportThrow = localName => {
  148. return _template.default.expression.ast`
  149. (function() {
  150. throw new Error('"' + '${localName}' + '" is read-only.');
  151. })()
  152. `;
  153. };
  154. const rewriteReferencesVisitor = {
  155. ReferencedIdentifier(path) {
  156. const {
  157. seen,
  158. buildImportReference,
  159. scope,
  160. imported,
  161. requeueInParent
  162. } = this;
  163. if (seen.has(path.node)) return;
  164. seen.add(path.node);
  165. const localName = path.node.name;
  166. const importData = imported.get(localName);
  167. if (importData) {
  168. if (isInType(path)) {
  169. throw path.buildCodeFrameError(`Cannot transform the imported binding "${localName}" since it's also used in a type annotation. ` + `Please strip type annotations using @babel/preset-typescript or @babel/preset-flow.`);
  170. }
  171. const localBinding = path.scope.getBinding(localName);
  172. const rootBinding = scope.getBinding(localName);
  173. if (rootBinding !== localBinding) return;
  174. const ref = buildImportReference(importData, path.node);
  175. ref.loc = path.node.loc;
  176. if ((path.parentPath.isCallExpression({
  177. callee: path.node
  178. }) || path.parentPath.isOptionalCallExpression({
  179. callee: path.node
  180. }) || path.parentPath.isTaggedTemplateExpression({
  181. tag: path.node
  182. })) && isMemberExpression(ref)) {
  183. path.replaceWith(sequenceExpression([numericLiteral(0), ref]));
  184. } else if (path.isJSXIdentifier() && isMemberExpression(ref)) {
  185. const {
  186. object,
  187. property
  188. } = ref;
  189. path.replaceWith(jsxMemberExpression(jsxIdentifier(object.name), jsxIdentifier(property.name)));
  190. } else {
  191. path.replaceWith(ref);
  192. }
  193. requeueInParent(path);
  194. path.skip();
  195. }
  196. },
  197. UpdateExpression(path) {
  198. const {
  199. scope,
  200. seen,
  201. imported,
  202. exported,
  203. requeueInParent,
  204. buildImportReference
  205. } = this;
  206. if (seen.has(path.node)) return;
  207. seen.add(path.node);
  208. const arg = path.get("argument");
  209. if (arg.isMemberExpression()) return;
  210. const update = path.node;
  211. if (arg.isIdentifier()) {
  212. const localName = arg.node.name;
  213. if (scope.getBinding(localName) !== path.scope.getBinding(localName)) {
  214. return;
  215. }
  216. const exportedNames = exported.get(localName);
  217. const importData = imported.get(localName);
  218. if ((exportedNames == null ? void 0 : exportedNames.length) > 0 || importData) {
  219. if (importData) {
  220. path.replaceWith(assignmentExpression(update.operator[0] + "=", buildImportReference(importData, arg.node), buildImportThrow(localName)));
  221. } else if (update.prefix) {
  222. path.replaceWith(buildBindingExportAssignmentExpression(this.metadata, exportedNames, cloneNode(update)));
  223. } else {
  224. const ref = scope.generateDeclaredUidIdentifier(localName);
  225. path.replaceWith(sequenceExpression([assignmentExpression("=", cloneNode(ref), cloneNode(update)), buildBindingExportAssignmentExpression(this.metadata, exportedNames, identifier(localName)), cloneNode(ref)]));
  226. }
  227. }
  228. }
  229. requeueInParent(path);
  230. path.skip();
  231. },
  232. AssignmentExpression: {
  233. exit(path) {
  234. const {
  235. scope,
  236. seen,
  237. imported,
  238. exported,
  239. requeueInParent,
  240. buildImportReference
  241. } = this;
  242. if (seen.has(path.node)) return;
  243. seen.add(path.node);
  244. const left = path.get("left");
  245. if (left.isMemberExpression()) return;
  246. if (left.isIdentifier()) {
  247. const localName = left.node.name;
  248. if (scope.getBinding(localName) !== path.scope.getBinding(localName)) {
  249. return;
  250. }
  251. const exportedNames = exported.get(localName);
  252. const importData = imported.get(localName);
  253. if ((exportedNames == null ? void 0 : exportedNames.length) > 0 || importData) {
  254. _assert(path.node.operator === "=", "Path was not simplified");
  255. const assignment = path.node;
  256. if (importData) {
  257. assignment.left = buildImportReference(importData, assignment.left);
  258. assignment.right = sequenceExpression([assignment.right, buildImportThrow(localName)]);
  259. }
  260. path.replaceWith(buildBindingExportAssignmentExpression(this.metadata, exportedNames, assignment));
  261. requeueInParent(path);
  262. }
  263. } else {
  264. const ids = left.getOuterBindingIdentifiers();
  265. const programScopeIds = Object.keys(ids).filter(localName => scope.getBinding(localName) === path.scope.getBinding(localName));
  266. const id = programScopeIds.find(localName => imported.has(localName));
  267. if (id) {
  268. path.node.right = sequenceExpression([path.node.right, buildImportThrow(id)]);
  269. }
  270. const items = [];
  271. programScopeIds.forEach(localName => {
  272. const exportedNames = exported.get(localName) || [];
  273. if (exportedNames.length > 0) {
  274. items.push(buildBindingExportAssignmentExpression(this.metadata, exportedNames, identifier(localName)));
  275. }
  276. });
  277. if (items.length > 0) {
  278. let node = sequenceExpression(items);
  279. if (path.parentPath.isExpressionStatement()) {
  280. node = expressionStatement(node);
  281. node._blockHoist = path.parentPath.node._blockHoist;
  282. }
  283. const statement = path.insertAfter(node)[0];
  284. requeueInParent(statement);
  285. }
  286. }
  287. }
  288. },
  289. "ForOfStatement|ForInStatement"(path) {
  290. const {
  291. scope,
  292. node
  293. } = path;
  294. const {
  295. left
  296. } = node;
  297. const {
  298. exported,
  299. imported,
  300. scope: programScope
  301. } = this;
  302. if (!isVariableDeclaration(left)) {
  303. let didTransformExport = false,
  304. importConstViolationName;
  305. const loopBodyScope = path.get("body").scope;
  306. for (const name of Object.keys(getOuterBindingIdentifiers(left))) {
  307. if (programScope.getBinding(name) === scope.getBinding(name)) {
  308. if (exported.has(name)) {
  309. didTransformExport = true;
  310. if (loopBodyScope.hasOwnBinding(name)) {
  311. loopBodyScope.rename(name);
  312. }
  313. }
  314. if (imported.has(name) && !importConstViolationName) {
  315. importConstViolationName = name;
  316. }
  317. }
  318. }
  319. if (!didTransformExport && !importConstViolationName) {
  320. return;
  321. }
  322. path.ensureBlock();
  323. const bodyPath = path.get("body");
  324. const newLoopId = scope.generateUidIdentifierBasedOnNode(left);
  325. path.get("left").replaceWith(variableDeclaration("let", [variableDeclarator(cloneNode(newLoopId))]));
  326. scope.registerDeclaration(path.get("left"));
  327. if (didTransformExport) {
  328. bodyPath.unshiftContainer("body", expressionStatement(assignmentExpression("=", left, newLoopId)));
  329. }
  330. if (importConstViolationName) {
  331. bodyPath.unshiftContainer("body", expressionStatement(buildImportThrow(importConstViolationName)));
  332. }
  333. }
  334. }
  335. };