rewrite-live-references.js 12 KB

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