| 1 |
import assert from "assert"; |
| 2 |
import { |
| 3 |
assignmentExpression, |
| 4 |
callExpression, |
| 5 |
cloneNode, |
| 6 |
expressionStatement, |
| 7 |
getOuterBindingIdentifiers, |
| 8 |
identifier, |
| 9 |
isMemberExpression, |
| 10 |
isVariableDeclaration, |
| 11 |
jsxIdentifier, |
| 12 |
jsxMemberExpression, |
| 13 |
memberExpression, |
| 14 |
numericLiteral, |
| 15 |
sequenceExpression, |
| 16 |
stringLiteral, |
| 17 |
variableDeclaration, |
| 18 |
variableDeclarator, |
| 19 |
} from "@babel/types"; |
| 20 |
import type * as t from "@babel/types"; |
| 21 |
import template from "@babel/template"; |
| 22 |
import type { NodePath, Visitor, Scope } from "@babel/traverse"; |
| 23 |
import simplifyAccess from "@babel/helper-simple-access"; |
| 24 |
|
| 25 |
import type { ModuleMetadata } from "./normalize-and-load-metadata"; |
| 26 |
|
| 27 |
interface RewriteReferencesVisitorState { |
| 28 |
exported: Map<any, any>; |
| 29 |
metadata: ModuleMetadata; |
| 30 |
requeueInParent: (path: NodePath) => void; |
| 31 |
scope: Scope; |
| 32 |
imported: Map<any, any>; |
| 33 |
buildImportReference: ( |
| 34 |
[source, importName, localName]: readonly [string, string, string], |
| 35 |
identNode: t.Identifier | t.CallExpression | t.JSXIdentifier, |
| 36 |
) => any; |
| 37 |
seen: WeakSet<object>; |
| 38 |
} |
| 39 |
|
| 40 |
interface RewriteBindingInitVisitorState { |
| 41 |
exported: Map<any, any>; |
| 42 |
metadata: ModuleMetadata; |
| 43 |
requeueInParent: (path: NodePath) => void; |
| 44 |
scope: Scope; |
| 45 |
} |
| 46 |
|
| 47 |
function isInType(path: NodePath) { |
| 48 |
do { |
| 49 |
switch (path.parent.type) { |
| 50 |
case "TSTypeAnnotation": |
| 51 |
case "TSTypeAliasDeclaration": |
| 52 |
case "TSTypeReference": |
| 53 |
case "TypeAnnotation": |
| 54 |
case "TypeAlias": |
| 55 |
return true; |
| 56 |
case "ExportSpecifier": |
| 57 |
return ( |
| 58 |
( |
| 59 |
path.parentPath.parent as |
| 60 |
| t.ExportDefaultDeclaration |
| 61 |
| t.ExportNamedDeclaration |
| 62 |
).exportKind === "type" |
| 63 |
); |
| 64 |
default: |
| 65 |
if (path.parentPath.isStatement() || path.parentPath.isExpression()) { |
| 66 |
return false; |
| 67 |
} |
| 68 |
} |
| 69 |
} while ((path = path.parentPath)); |
| 70 |
} |
| 71 |
|
| 72 |
export default function rewriteLiveReferences( |
| 73 |
programPath: NodePath<t.Program>, |
| 74 |
metadata: ModuleMetadata, |
| 75 |
) { |
| 76 |
const imported = new Map(); |
| 77 |
const exported = new Map(); |
| 78 |
const requeueInParent = (path: NodePath) => { |
| 79 |
// Manually re-queue `exports.default =` expressions so that the ES3 |
| 80 |
// transform has an opportunity to convert them. Ideally this would |
| 81 |
// happen automatically from the replaceWith above. See #4140 for |
| 82 |
// more info. |
| 83 |
programPath.requeue(path); |
| 84 |
}; |
| 85 |
|
| 86 |
for (const [source, data] of metadata.source) { |
| 87 |
for (const [localName, importName] of data.imports) { |
| 88 |
imported.set(localName, [source, importName, null]); |
| 89 |
} |
| 90 |
for (const localName of data.importsNamespace) { |
| 91 |
imported.set(localName, [source, null, localName]); |
| 92 |
} |
| 93 |
} |
| 94 |
|
| 95 |
for (const [local, data] of metadata.local) { |
| 96 |
let exportMeta = exported.get(local); |
| 97 |
if (!exportMeta) { |
| 98 |
exportMeta = []; |
| 99 |
exported.set(local, exportMeta); |
| 100 |
} |
| 101 |
|
| 102 |
exportMeta.push(...data.names); |
| 103 |
} |
| 104 |
|
| 105 |
// Rewrite initialization of bindings to update exports. |
| 106 |
const rewriteBindingInitVisitorState: RewriteBindingInitVisitorState = { |
| 107 |
metadata, |
| 108 |
requeueInParent, |
| 109 |
scope: programPath.scope, |
| 110 |
exported, // local name => exported name list |
| 111 |
}; |
| 112 |
programPath.traverse( |
| 113 |
// eslint-disable-next-line @typescript-eslint/no-use-before-define |
| 114 |
rewriteBindingInitVisitor, |
| 115 |
rewriteBindingInitVisitorState, |
| 116 |
); |
| 117 |
|
| 118 |
simplifyAccess( |
| 119 |
programPath, |
| 120 |
// NOTE(logan): The 'Array.from' calls are to make this code with in loose mode. |
| 121 |
new Set([...Array.from(imported.keys()), ...Array.from(exported.keys())]), |
| 122 |
false, |
| 123 |
); |
| 124 |
|
| 125 |
// Rewrite reads/writes from imports and exports to have the correct behavior. |
| 126 |
const rewriteReferencesVisitorState: RewriteReferencesVisitorState = { |
| 127 |
seen: new WeakSet(), |
| 128 |
metadata, |
| 129 |
requeueInParent, |
| 130 |
scope: programPath.scope, |
| 131 |
imported, // local / import |
| 132 |
exported, // local name => exported name list |
| 133 |
buildImportReference: ([source, importName, localName], identNode) => { |
| 134 |
const meta = metadata.source.get(source); |
| 135 |
|
| 136 |
if (localName) { |
| 137 |
if (meta.lazy) { |
| 138 |
identNode = callExpression( |
| 139 |
// @ts-expect-error Fixme: we should handle the case when identNode is a JSXIdentifier |
| 140 |
identNode, |
| 141 |
[], |
| 142 |
); |
| 143 |
} |
| 144 |
return identNode; |
| 145 |
} |
| 146 |
|
| 147 |
let namespace: t.Expression = identifier(meta.name); |
| 148 |
if (meta.lazy) namespace = callExpression(namespace, []); |
| 149 |
|
| 150 |
if (importName === "default" && meta.interop === "node-default") { |
| 151 |
return namespace; |
| 152 |
} |
| 153 |
|
| 154 |
const computed = metadata.stringSpecifiers.has(importName); |
| 155 |
|
| 156 |
return memberExpression( |
| 157 |
namespace, |
| 158 |
computed ? stringLiteral(importName) : identifier(importName), |
| 159 |
computed, |
| 160 |
); |
| 161 |
}, |
| 162 |
}; |
| 163 |
// eslint-disable-next-line @typescript-eslint/no-use-before-define |
| 164 |
programPath.traverse(rewriteReferencesVisitor, rewriteReferencesVisitorState); |
| 165 |
} |
| 166 |
|
| 167 |
/** |
| 168 |
* A visitor to inject export update statements during binding initialization. |
| 169 |
*/ |
| 170 |
const rewriteBindingInitVisitor: Visitor<RewriteBindingInitVisitorState> = { |
| 171 |
Scope(path) { |
| 172 |
path.skip(); |
| 173 |
}, |
| 174 |
ClassDeclaration(path) { |
| 175 |
const { requeueInParent, exported, metadata } = this; |
| 176 |
|
| 177 |
const { id } = path.node; |
| 178 |
if (!id) throw new Error("Expected class to have a name"); |
| 179 |
const localName = id.name; |
| 180 |
|
| 181 |
const exportNames = exported.get(localName) || []; |
| 182 |
if (exportNames.length > 0) { |
| 183 |
const statement = expressionStatement( |
| 184 |
// eslint-disable-next-line @typescript-eslint/no-use-before-define |
| 185 |
buildBindingExportAssignmentExpression( |
| 186 |
metadata, |
| 187 |
exportNames, |
| 188 |
identifier(localName), |
| 189 |
path.scope, |
| 190 |
), |
| 191 |
); |
| 192 |
// @ts-expect-error todo(flow->ts): avoid mutations |
| 193 |
statement._blockHoist = path.node._blockHoist; |
| 194 |
|
| 195 |
requeueInParent(path.insertAfter(statement)[0]); |
| 196 |
} |
| 197 |
}, |
| 198 |
VariableDeclaration(path) { |
| 199 |
const { requeueInParent, exported, metadata } = this; |
| 200 |
|
| 201 |
Object.keys(path.getOuterBindingIdentifiers()).forEach(localName => { |
| 202 |
const exportNames = exported.get(localName) || []; |
| 203 |
|
| 204 |
if (exportNames.length > 0) { |
| 205 |
const statement = expressionStatement( |
| 206 |
// eslint-disable-next-line @typescript-eslint/no-use-before-define |
| 207 |
buildBindingExportAssignmentExpression( |
| 208 |
metadata, |
| 209 |
exportNames, |
| 210 |
identifier(localName), |
| 211 |
path.scope, |
| 212 |
), |
| 213 |
); |
| 214 |
// @ts-expect-error todo(flow->ts): avoid mutations |
| 215 |
statement._blockHoist = path.node._blockHoist; |
| 216 |
|
| 217 |
requeueInParent(path.insertAfter(statement)[0]); |
| 218 |
} |
| 219 |
}); |
| 220 |
}, |
| 221 |
}; |
| 222 |
|
| 223 |
const buildBindingExportAssignmentExpression = ( |
| 224 |
metadata: ModuleMetadata, |
| 225 |
exportNames: string[], |
| 226 |
localExpr: t.Expression, |
| 227 |
scope: Scope, |
| 228 |
) => { |
| 229 |
const exportsObjectName = metadata.exportName; |
| 230 |
for ( |
| 231 |
let currentScope = scope; |
| 232 |
currentScope != null; |
| 233 |
currentScope = currentScope.parent |
| 234 |
) { |
| 235 |
if (currentScope.hasOwnBinding(exportsObjectName)) { |
| 236 |
currentScope.rename(exportsObjectName); |
| 237 |
} |
| 238 |
} |
| 239 |
return (exportNames || []).reduce((expr, exportName) => { |
| 240 |
// class Foo {} export { Foo, Foo as Bar }; |
| 241 |
// as |
| 242 |
// class Foo {} exports.Foo = exports.Bar = Foo; |
| 243 |
const { stringSpecifiers } = metadata; |
| 244 |
const computed = stringSpecifiers.has(exportName); |
| 245 |
return assignmentExpression( |
| 246 |
"=", |
| 247 |
memberExpression( |
| 248 |
identifier(exportsObjectName), |
| 249 |
computed ? stringLiteral(exportName) : identifier(exportName), |
| 250 |
/* computed */ computed, |
| 251 |
), |
| 252 |
expr, |
| 253 |
); |
| 254 |
}, localExpr); |
| 255 |
}; |
| 256 |
|
| 257 |
const buildImportThrow = (localName: string) => { |
| 258 |
return template.expression.ast` |
| 259 |
(function() { |
| 260 |
throw new Error('"' + '${localName}' + '" is read-only.'); |
| 261 |
})() |
| 262 |
`; |
| 263 |
}; |
| 264 |
|
| 265 |
const rewriteReferencesVisitor: Visitor<RewriteReferencesVisitorState> = { |
| 266 |
ReferencedIdentifier(path) { |
| 267 |
const { seen, buildImportReference, scope, imported, requeueInParent } = |
| 268 |
this; |
| 269 |
if (seen.has(path.node)) return; |
| 270 |
seen.add(path.node); |
| 271 |
|
| 272 |
const localName = path.node.name; |
| 273 |
|
| 274 |
const importData = imported.get(localName); |
| 275 |
if (importData) { |
| 276 |
if (isInType(path)) { |
| 277 |
throw path.buildCodeFrameError( |
| 278 |
`Cannot transform the imported binding "${localName}" since it's also used in a type annotation. ` + |
| 279 |
`Please strip type annotations using @babel/preset-typescript or @babel/preset-flow.`, |
| 280 |
); |
| 281 |
} |
| 282 |
|
| 283 |
const localBinding = path.scope.getBinding(localName); |
| 284 |
const rootBinding = scope.getBinding(localName); |
| 285 |
|
| 286 |
// redeclared in this scope |
| 287 |
if (rootBinding !== localBinding) return; |
| 288 |
|
| 289 |
const ref = buildImportReference(importData, path.node); |
| 290 |
|
| 291 |
// Preserve the binding location so that sourcemaps are nicer. |
| 292 |
ref.loc = path.node.loc; |
| 293 |
|
| 294 |
if ( |
| 295 |
(path.parentPath.isCallExpression({ callee: path.node }) || |
| 296 |
path.parentPath.isOptionalCallExpression({ callee: path.node }) || |
| 297 |
path.parentPath.isTaggedTemplateExpression({ tag: path.node })) && |
| 298 |
isMemberExpression(ref) |
| 299 |
) { |
| 300 |
path.replaceWith(sequenceExpression([numericLiteral(0), ref])); |
| 301 |
} else if (path.isJSXIdentifier() && isMemberExpression(ref)) { |
| 302 |
const { object, property } = ref; |
| 303 |
path.replaceWith( |
| 304 |
jsxMemberExpression( |
| 305 |
// @ts-expect-error todo(flow->ts): possible bug `object` might not have a name |
| 306 |
jsxIdentifier(object.name), |
| 307 |
// @ts-expect-error todo(flow->ts): possible bug `property` might not have a name |
| 308 |
jsxIdentifier(property.name), |
| 309 |
), |
| 310 |
); |
| 311 |
} else { |
| 312 |
path.replaceWith(ref); |
| 313 |
} |
| 314 |
|
| 315 |
requeueInParent(path); |
| 316 |
|
| 317 |
// The path could have been replaced with an identifier that would |
| 318 |
// otherwise be re-visited, so we skip processing its children. |
| 319 |
path.skip(); |
| 320 |
} |
| 321 |
}, |
| 322 |
|
| 323 |
UpdateExpression(path) { |
| 324 |
const { |
| 325 |
scope, |
| 326 |
seen, |
| 327 |
imported, |
| 328 |
exported, |
| 329 |
requeueInParent, |
| 330 |
buildImportReference, |
| 331 |
} = this; |
| 332 |
|
| 333 |
if (seen.has(path.node)) return; |
| 334 |
|
| 335 |
seen.add(path.node); |
| 336 |
|
| 337 |
const arg = path.get("argument"); |
| 338 |
|
| 339 |
// No change needed |
| 340 |
if (arg.isMemberExpression()) return; |
| 341 |
|
| 342 |
const update = path.node; |
| 343 |
|
| 344 |
if (arg.isIdentifier()) { |
| 345 |
const localName = arg.node.name; |
| 346 |
|
| 347 |
// redeclared in this scope |
| 348 |
if (scope.getBinding(localName) !== path.scope.getBinding(localName)) { |
| 349 |
return; |
| 350 |
} |
| 351 |
|
| 352 |
const exportedNames = exported.get(localName); |
| 353 |
const importData = imported.get(localName); |
| 354 |
|
| 355 |
if (exportedNames?.length > 0 || importData) { |
| 356 |
if (importData) { |
| 357 |
path.replaceWith( |
| 358 |
assignmentExpression( |
| 359 |
update.operator[0] + "=", |
| 360 |
buildImportReference(importData, arg.node), |
| 361 |
buildImportThrow(localName), |
| 362 |
), |
| 363 |
); |
| 364 |
} else if (update.prefix) { |
| 365 |
// ++foo |
| 366 |
// => exports.foo = ++foo |
| 367 |
path.replaceWith( |
| 368 |
buildBindingExportAssignmentExpression( |
| 369 |
this.metadata, |
| 370 |
exportedNames, |
| 371 |
cloneNode(update), |
| 372 |
path.scope, |
| 373 |
), |
| 374 |
); |
| 375 |
} else { |
| 376 |
// foo++ |
| 377 |
// => (ref = i++, exports.i = i, ref) |
| 378 |
const ref = scope.generateDeclaredUidIdentifier(localName); |
| 379 |
|
| 380 |
path.replaceWith( |
| 381 |
sequenceExpression([ |
| 382 |
assignmentExpression("=", cloneNode(ref), cloneNode(update)), |
| 383 |
buildBindingExportAssignmentExpression( |
| 384 |
this.metadata, |
| 385 |
exportedNames, |
| 386 |
identifier(localName), |
| 387 |
path.scope, |
| 388 |
), |
| 389 |
cloneNode(ref), |
| 390 |
]), |
| 391 |
); |
| 392 |
} |
| 393 |
} |
| 394 |
} |
| 395 |
|
| 396 |
requeueInParent(path); |
| 397 |
path.skip(); |
| 398 |
}, |
| 399 |
|
| 400 |
AssignmentExpression: { |
| 401 |
exit(path) { |
| 402 |
const { |
| 403 |
scope, |
| 404 |
seen, |
| 405 |
imported, |
| 406 |
exported, |
| 407 |
requeueInParent, |
| 408 |
buildImportReference, |
| 409 |
} = this; |
| 410 |
|
| 411 |
if (seen.has(path.node)) return; |
| 412 |
seen.add(path.node); |
| 413 |
|
| 414 |
const left = path.get("left"); |
| 415 |
|
| 416 |
// No change needed |
| 417 |
if (left.isMemberExpression()) return; |
| 418 |
|
| 419 |
if (left.isIdentifier()) { |
| 420 |
// Simple update-assign foo += 1; export { foo }; |
| 421 |
// => exports.foo = (foo += 1); |
| 422 |
const localName = left.node.name; |
| 423 |
|
| 424 |
// redeclared in this scope |
| 425 |
if (scope.getBinding(localName) !== path.scope.getBinding(localName)) { |
| 426 |
return; |
| 427 |
} |
| 428 |
|
| 429 |
const exportedNames = exported.get(localName); |
| 430 |
const importData = imported.get(localName); |
| 431 |
if (exportedNames?.length > 0 || importData) { |
| 432 |
assert(path.node.operator === "=", "Path was not simplified"); |
| 433 |
|
| 434 |
const assignment = path.node; |
| 435 |
|
| 436 |
if (importData) { |
| 437 |
assignment.left = buildImportReference(importData, left.node); |
| 438 |
|
| 439 |
assignment.right = sequenceExpression([ |
| 440 |
assignment.right, |
| 441 |
buildImportThrow(localName), |
| 442 |
]); |
| 443 |
} |
| 444 |
|
| 445 |
path.replaceWith( |
| 446 |
buildBindingExportAssignmentExpression( |
| 447 |
this.metadata, |
| 448 |
exportedNames, |
| 449 |
assignment, |
| 450 |
path.scope, |
| 451 |
), |
| 452 |
); |
| 453 |
requeueInParent(path); |
| 454 |
} |
| 455 |
} else { |
| 456 |
const ids = left.getOuterBindingIdentifiers(); |
| 457 |
const programScopeIds = Object.keys(ids).filter( |
| 458 |
localName => |
| 459 |
scope.getBinding(localName) === path.scope.getBinding(localName), |
| 460 |
); |
| 461 |
const id = programScopeIds.find(localName => imported.has(localName)); |
| 462 |
|
| 463 |
if (id) { |
| 464 |
path.node.right = sequenceExpression([ |
| 465 |
path.node.right, |
| 466 |
buildImportThrow(id), |
| 467 |
]); |
| 468 |
} |
| 469 |
|
| 470 |
// Complex ({a, b, c} = {}); export { a, c }; |
| 471 |
// => ({a, b, c} = {}), (exports.a = a, exports.c = c); |
| 472 |
const items: t.Expression[] = []; |
| 473 |
programScopeIds.forEach(localName => { |
| 474 |
const exportedNames = exported.get(localName) || []; |
| 475 |
if (exportedNames.length > 0) { |
| 476 |
items.push( |
| 477 |
buildBindingExportAssignmentExpression( |
| 478 |
this.metadata, |
| 479 |
exportedNames, |
| 480 |
identifier(localName), |
| 481 |
path.scope, |
| 482 |
), |
| 483 |
); |
| 484 |
} |
| 485 |
}); |
| 486 |
|
| 487 |
if (items.length > 0) { |
| 488 |
let node: t.Node = sequenceExpression(items); |
| 489 |
if (path.parentPath.isExpressionStatement()) { |
| 490 |
node = expressionStatement(node); |
| 491 |
// @ts-expect-error todo(flow->ts): avoid mutations |
| 492 |
node._blockHoist = path.parentPath.node._blockHoist; |
| 493 |
} |
| 494 |
|
| 495 |
const statement = path.insertAfter(node)[0]; |
| 496 |
requeueInParent(statement); |
| 497 |
} |
| 498 |
} |
| 499 |
}, |
| 500 |
}, |
| 501 |
"ForOfStatement|ForInStatement"( |
| 502 |
path: NodePath<t.ForOfStatement | t.ForInStatement>, |
| 503 |
) { |
| 504 |
const { scope, node } = path; |
| 505 |
const { left } = node; |
| 506 |
const { exported, imported, scope: programScope } = this; |
| 507 |
|
| 508 |
if (!isVariableDeclaration(left)) { |
| 509 |
let didTransformExport = false, |
| 510 |
importConstViolationName; |
| 511 |
const loopBodyScope = path.get("body").scope; |
| 512 |
for (const name of Object.keys(getOuterBindingIdentifiers(left))) { |
| 513 |
if (programScope.getBinding(name) === scope.getBinding(name)) { |
| 514 |
if (exported.has(name)) { |
| 515 |
didTransformExport = true; |
| 516 |
if (loopBodyScope.hasOwnBinding(name)) { |
| 517 |
loopBodyScope.rename(name); |
| 518 |
} |
| 519 |
} |
| 520 |
if (imported.has(name) && !importConstViolationName) { |
| 521 |
importConstViolationName = name; |
| 522 |
} |
| 523 |
} |
| 524 |
} |
| 525 |
if (!didTransformExport && !importConstViolationName) { |
| 526 |
return; |
| 527 |
} |
| 528 |
|
| 529 |
path.ensureBlock(); |
| 530 |
const bodyPath = path.get("body"); |
| 531 |
|
| 532 |
const newLoopId = scope.generateUidIdentifierBasedOnNode(left); |
| 533 |
path |
| 534 |
.get("left") |
| 535 |
.replaceWith( |
| 536 |
variableDeclaration("let", [ |
| 537 |
variableDeclarator(cloneNode(newLoopId)), |
| 538 |
]), |
| 539 |
); |
| 540 |
scope.registerDeclaration(path.get("left")); |
| 541 |
|
| 542 |
if (didTransformExport) { |
| 543 |
bodyPath.unshiftContainer( |
| 544 |
"body", |
| 545 |
expressionStatement(assignmentExpression("=", left, newLoopId)), |
| 546 |
); |
| 547 |
} |
| 548 |
if (importConstViolationName) { |
| 549 |
bodyPath.unshiftContainer( |
| 550 |
"body", |
| 551 |
expressionStatement(buildImportThrow(importConstViolationName)), |
| 552 |
); |
| 553 |
} |
| 554 |
} |
| 555 |
}, |
| 556 |
}; |