rewrite-live-references.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. meta.referenced = true;
  86. if (localName) {
  87. if (meta.lazy) {
  88. identNode = callExpression(identNode, []);
  89. }
  90. return identNode;
  91. }
  92. let namespace = identifier(meta.name);
  93. if (meta.lazy) namespace = callExpression(namespace, []);
  94. if (importName === "default" && meta.interop === "node-default") {
  95. return namespace;
  96. }
  97. const computed = metadata.stringSpecifiers.has(importName);
  98. return memberExpression(namespace, computed ? stringLiteral(importName) : identifier(importName), computed);
  99. }
  100. };
  101. programPath.traverse(rewriteReferencesVisitor, rewriteReferencesVisitorState);
  102. }
  103. const rewriteBindingInitVisitor = {
  104. Scope(path) {
  105. path.skip();
  106. },
  107. ClassDeclaration(path) {
  108. const {
  109. requeueInParent,
  110. exported,
  111. metadata
  112. } = this;
  113. const {
  114. id
  115. } = path.node;
  116. if (!id) throw new Error("Expected class to have a name");
  117. const localName = id.name;
  118. const exportNames = exported.get(localName) || [];
  119. if (exportNames.length > 0) {
  120. const statement = expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, identifier(localName), path.scope));
  121. statement._blockHoist = path.node._blockHoist;
  122. requeueInParent(path.insertAfter(statement)[0]);
  123. }
  124. },
  125. VariableDeclaration(path) {
  126. const {
  127. requeueInParent,
  128. exported,
  129. metadata
  130. } = this;
  131. Object.keys(path.getOuterBindingIdentifiers()).forEach(localName => {
  132. const exportNames = exported.get(localName) || [];
  133. if (exportNames.length > 0) {
  134. const statement = expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, identifier(localName), path.scope));
  135. statement._blockHoist = path.node._blockHoist;
  136. requeueInParent(path.insertAfter(statement)[0]);
  137. }
  138. });
  139. }
  140. };
  141. const buildBindingExportAssignmentExpression = (metadata, exportNames, localExpr, scope) => {
  142. const exportsObjectName = metadata.exportName;
  143. for (let currentScope = scope; currentScope != null; currentScope = currentScope.parent) {
  144. if (currentScope.hasOwnBinding(exportsObjectName)) {
  145. currentScope.rename(exportsObjectName);
  146. }
  147. }
  148. return (exportNames || []).reduce((expr, exportName) => {
  149. const {
  150. stringSpecifiers
  151. } = metadata;
  152. const computed = stringSpecifiers.has(exportName);
  153. return assignmentExpression("=", memberExpression(identifier(exportsObjectName), computed ? stringLiteral(exportName) : identifier(exportName), computed), expr);
  154. }, localExpr);
  155. };
  156. const buildImportThrow = localName => {
  157. return _template.default.expression.ast`
  158. (function() {
  159. throw new Error('"' + '${localName}' + '" is read-only.');
  160. })()
  161. `;
  162. };
  163. const rewriteReferencesVisitor = {
  164. ReferencedIdentifier(path) {
  165. const {
  166. seen,
  167. buildImportReference,
  168. scope,
  169. imported,
  170. requeueInParent
  171. } = this;
  172. if (seen.has(path.node)) return;
  173. seen.add(path.node);
  174. const localName = path.node.name;
  175. const importData = imported.get(localName);
  176. if (importData) {
  177. if (isInType(path)) {
  178. 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.`);
  179. }
  180. const localBinding = path.scope.getBinding(localName);
  181. const rootBinding = scope.getBinding(localName);
  182. if (rootBinding !== localBinding) return;
  183. const ref = buildImportReference(importData, path.node);
  184. ref.loc = path.node.loc;
  185. if ((path.parentPath.isCallExpression({
  186. callee: path.node
  187. }) || path.parentPath.isOptionalCallExpression({
  188. callee: path.node
  189. }) || path.parentPath.isTaggedTemplateExpression({
  190. tag: path.node
  191. })) && isMemberExpression(ref)) {
  192. path.replaceWith(sequenceExpression([numericLiteral(0), ref]));
  193. } else if (path.isJSXIdentifier() && isMemberExpression(ref)) {
  194. const {
  195. object,
  196. property
  197. } = ref;
  198. path.replaceWith(jsxMemberExpression(jsxIdentifier(object.name), jsxIdentifier(property.name)));
  199. } else {
  200. path.replaceWith(ref);
  201. }
  202. requeueInParent(path);
  203. path.skip();
  204. }
  205. },
  206. UpdateExpression(path) {
  207. const {
  208. scope,
  209. seen,
  210. imported,
  211. exported,
  212. requeueInParent,
  213. buildImportReference
  214. } = this;
  215. if (seen.has(path.node)) return;
  216. seen.add(path.node);
  217. const arg = path.get("argument");
  218. if (arg.isMemberExpression()) return;
  219. const update = path.node;
  220. if (arg.isIdentifier()) {
  221. const localName = arg.node.name;
  222. if (scope.getBinding(localName) !== path.scope.getBinding(localName)) {
  223. return;
  224. }
  225. const exportedNames = exported.get(localName);
  226. const importData = imported.get(localName);
  227. if ((exportedNames == null ? void 0 : exportedNames.length) > 0 || importData) {
  228. if (importData) {
  229. path.replaceWith(assignmentExpression(update.operator[0] + "=", buildImportReference(importData, arg.node), buildImportThrow(localName)));
  230. } else if (update.prefix) {
  231. path.replaceWith(buildBindingExportAssignmentExpression(this.metadata, exportedNames, cloneNode(update), path.scope));
  232. } else {
  233. const ref = scope.generateDeclaredUidIdentifier(localName);
  234. path.replaceWith(sequenceExpression([assignmentExpression("=", cloneNode(ref), cloneNode(update)), buildBindingExportAssignmentExpression(this.metadata, exportedNames, identifier(localName), path.scope), cloneNode(ref)]));
  235. }
  236. }
  237. }
  238. requeueInParent(path);
  239. path.skip();
  240. },
  241. AssignmentExpression: {
  242. exit(path) {
  243. const {
  244. scope,
  245. seen,
  246. imported,
  247. exported,
  248. requeueInParent,
  249. buildImportReference
  250. } = this;
  251. if (seen.has(path.node)) return;
  252. seen.add(path.node);
  253. const left = path.get("left");
  254. if (left.isMemberExpression()) return;
  255. if (left.isIdentifier()) {
  256. const localName = left.node.name;
  257. if (scope.getBinding(localName) !== path.scope.getBinding(localName)) {
  258. return;
  259. }
  260. const exportedNames = exported.get(localName);
  261. const importData = imported.get(localName);
  262. if ((exportedNames == null ? void 0 : exportedNames.length) > 0 || importData) {
  263. _assert(path.node.operator === "=", "Path was not simplified");
  264. const assignment = path.node;
  265. if (importData) {
  266. assignment.left = buildImportReference(importData, left.node);
  267. assignment.right = sequenceExpression([assignment.right, buildImportThrow(localName)]);
  268. }
  269. path.replaceWith(buildBindingExportAssignmentExpression(this.metadata, exportedNames, assignment, path.scope));
  270. requeueInParent(path);
  271. }
  272. } else {
  273. const ids = left.getOuterBindingIdentifiers();
  274. const programScopeIds = Object.keys(ids).filter(localName => scope.getBinding(localName) === path.scope.getBinding(localName));
  275. const id = programScopeIds.find(localName => imported.has(localName));
  276. if (id) {
  277. path.node.right = sequenceExpression([path.node.right, buildImportThrow(id)]);
  278. }
  279. const items = [];
  280. programScopeIds.forEach(localName => {
  281. const exportedNames = exported.get(localName) || [];
  282. if (exportedNames.length > 0) {
  283. items.push(buildBindingExportAssignmentExpression(this.metadata, exportedNames, identifier(localName), path.scope));
  284. }
  285. });
  286. if (items.length > 0) {
  287. let node = sequenceExpression(items);
  288. if (path.parentPath.isExpressionStatement()) {
  289. node = expressionStatement(node);
  290. node._blockHoist = path.parentPath.node._blockHoist;
  291. }
  292. const statement = path.insertAfter(node)[0];
  293. requeueInParent(statement);
  294. }
  295. }
  296. }
  297. },
  298. "ForOfStatement|ForInStatement"(path) {
  299. const {
  300. scope,
  301. node
  302. } = path;
  303. const {
  304. left
  305. } = node;
  306. const {
  307. exported,
  308. imported,
  309. scope: programScope
  310. } = this;
  311. if (!isVariableDeclaration(left)) {
  312. let didTransformExport = false,
  313. importConstViolationName;
  314. const loopBodyScope = path.get("body").scope;
  315. for (const name of Object.keys(getOuterBindingIdentifiers(left))) {
  316. if (programScope.getBinding(name) === scope.getBinding(name)) {
  317. if (exported.has(name)) {
  318. didTransformExport = true;
  319. if (loopBodyScope.hasOwnBinding(name)) {
  320. loopBodyScope.rename(name);
  321. }
  322. }
  323. if (imported.has(name) && !importConstViolationName) {
  324. importConstViolationName = name;
  325. }
  326. }
  327. }
  328. if (!didTransformExport && !importConstViolationName) {
  329. return;
  330. }
  331. path.ensureBlock();
  332. const bodyPath = path.get("body");
  333. const newLoopId = scope.generateUidIdentifierBasedOnNode(left);
  334. path.get("left").replaceWith(variableDeclaration("let", [variableDeclarator(cloneNode(newLoopId))]));
  335. scope.registerDeclaration(path.get("left"));
  336. if (didTransformExport) {
  337. bodyPath.unshiftContainer("body", expressionStatement(assignmentExpression("=", left, newLoopId)));
  338. }
  339. if (importConstViolationName) {
  340. bodyPath.unshiftContainer("body", expressionStatement(buildImportThrow(importConstViolationName)));
  341. }
  342. }
  343. }
  344. };
  345. //# sourceMappingURL=rewrite-live-references.js.map