rewrite-live-references.js 12 KB

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