| 1 | // This file contains methods that convert the path node into another node or some other type of data. |
| 2 | |
| 3 | import { |
| 4 | arrowFunctionExpression, |
| 5 | assignmentExpression, |
| 6 | binaryExpression, |
| 7 | blockStatement, |
| 8 | callExpression, |
| 9 | conditionalExpression, |
| 10 | expressionStatement, |
| 11 | identifier, |
| 12 | isIdentifier, |
| 13 | jsxIdentifier, |
| 14 | logicalExpression, |
| 15 | LOGICAL_OPERATORS, |
| 16 | memberExpression, |
| 17 | metaProperty, |
| 18 | numericLiteral, |
| 19 | objectExpression, |
| 20 | restElement, |
| 21 | returnStatement, |
| 22 | sequenceExpression, |
| 23 | spreadElement, |
| 24 | stringLiteral, |
| 25 | super as _super, |
| 26 | thisExpression, |
| 27 | toExpression, |
| 28 | unaryExpression, |
| 29 | } from "@babel/types"; |
| 30 | import type * as t from "@babel/types"; |
| 31 | import environmentVisitor from "@babel/helper-environment-visitor"; |
| 32 | import nameFunction from "@babel/helper-function-name"; |
| 33 | import { merge as mergeVisitors } from "../visitors"; |
| 34 | import type NodePath from "./index"; |
| 35 | |
| 36 | export function toComputedKey(this: NodePath) { |
| 37 | let key; |
| 38 | if (this.isMemberExpression()) { |
| 39 | key = this.node.property; |
| 40 | } else if (this.isProperty() || this.isMethod()) { |
| 41 | key = this.node.key; |
| 42 | } else { |
| 43 | throw new ReferenceError("todo"); |
| 44 | } |
| 45 | |
| 46 | // @ts-expect-error todo(flow->ts) computed does not exist in ClassPrivateProperty |
| 47 | if (!this.node.computed) { |
| 48 | if (isIdentifier(key)) key = stringLiteral(key.name); |
| 49 | } |
| 50 | |
| 51 | return key; |
| 52 | } |
| 53 | |
| 54 | export function ensureBlock( |
| 55 | this: NodePath< |
| 56 | t.Loop | t.WithStatement | t.Function | t.LabeledStatement | t.CatchClause |
| 57 | >, |
| 58 | ) { |
| 59 | const body = this.get("body"); |
| 60 | const bodyNode = body.node; |
| 61 | |
| 62 | if (Array.isArray(body)) { |
| 63 | throw new Error("Can't convert array path to a block statement"); |
| 64 | } |
| 65 | if (!bodyNode) { |
| 66 | throw new Error("Can't convert node without a body"); |
| 67 | } |
| 68 | |
| 69 | if (body.isBlockStatement()) { |
| 70 | return bodyNode; |
| 71 | } |
| 72 | |
| 73 | const statements: Array<t.Statement> = []; |
| 74 | |
| 75 | let stringPath = "body"; |
| 76 | let key; |
| 77 | let listKey; |
| 78 | if (body.isStatement()) { |
| 79 | listKey = "body"; |
| 80 | key = 0; |
| 81 | statements.push(body.node); |
| 82 | } else { |
| 83 | stringPath += ".body.0"; |
| 84 | if (this.isFunction()) { |
| 85 | key = "argument"; |
| 86 | statements.push(returnStatement(body.node as t.Expression)); |
| 87 | } else { |
| 88 | key = "expression"; |
| 89 | statements.push(expressionStatement(body.node as t.Expression)); |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | this.node.body = blockStatement(statements); |
| 94 | const parentPath = this.get(stringPath) as NodePath; |
| 95 | body.setup( |
| 96 | parentPath, |
| 97 | listKey |
| 98 | ? // @ts-expect-error listKey must present in parent path |
| 99 | parentPath.node[listKey] |
| 100 | : parentPath.node, |
| 101 | listKey, |
| 102 | key, |
| 103 | ); |
| 104 | |
| 105 | return this.node; |
| 106 | } |
| 107 | |
| 108 | /** |
| 109 | * Keeping this for backward-compatibility. You should use arrowFunctionToExpression() for >=7.x. |
| 110 | */ |
| 111 | // TODO(Babel 8): Remove this |
| 112 | export function arrowFunctionToShadowed(this: NodePath) { |
| 113 | if (!this.isArrowFunctionExpression()) return; |
| 114 | |
| 115 | this.arrowFunctionToExpression(); |
| 116 | } |
| 117 | |
| 118 | /** |
| 119 | * Given an arbitrary function, process its content as if it were an arrow function, moving references |
| 120 | * to "this", "arguments", "super", and such into the function's parent scope. This method is useful if |
| 121 | * you have wrapped some set of items in an IIFE or other function, but want "this", "arguments", and super" |
| 122 | * to continue behaving as expected. |
| 123 | */ |
| 124 | export function unwrapFunctionEnvironment(this: NodePath) { |
| 125 | if ( |
| 126 | !this.isArrowFunctionExpression() && |
| 127 | !this.isFunctionExpression() && |
| 128 | !this.isFunctionDeclaration() |
| 129 | ) { |
| 130 | throw this.buildCodeFrameError( |
| 131 | "Can only unwrap the environment of a function.", |
| 132 | ); |
| 133 | } |
| 134 | |
| 135 | hoistFunctionEnvironment(this); |
| 136 | } |
| 137 | |
| 138 | function setType<N extends t.Node, T extends N["type"]>( |
| 139 | path: NodePath<N>, |
| 140 | type: T, |
| 141 | ): asserts path is NodePath<Extract<N, { type: T }>> { |
| 142 | path.node.type = type; |
| 143 | } |
| 144 | |
| 145 | /** |
| 146 | * Convert a given arrow function into a normal ES5 function expression. |
| 147 | */ |
| 148 | export function arrowFunctionToExpression( |
| 149 | this: NodePath<t.ArrowFunctionExpression>, |
| 150 | { |
| 151 | allowInsertArrow = true, |
| 152 | allowInsertArrowWithRest = allowInsertArrow, |
| 153 | /** @deprecated Use `noNewArrows` instead */ |
| 154 | specCompliant = false, |
| 155 | // TODO(Babel 8): Consider defaulting to `false` for spec compliancy |
| 156 | noNewArrows = !specCompliant, |
| 157 | }: { |
| 158 | allowInsertArrow?: boolean | void; |
| 159 | allowInsertArrowWithRest?: boolean | void; |
| 160 | specCompliant?: boolean | void; |
| 161 | noNewArrows?: boolean; |
| 162 | } = {}, |
| 163 | ): NodePath< |
| 164 | Exclude<t.Function, t.Method | t.ArrowFunctionExpression> | t.CallExpression |
| 165 | > { |
| 166 | if (!this.isArrowFunctionExpression()) { |
| 167 | throw (this as NodePath).buildCodeFrameError( |
| 168 | "Cannot convert non-arrow function to a function expression.", |
| 169 | ); |
| 170 | } |
| 171 | |
| 172 | const { thisBinding, fnPath: fn } = hoistFunctionEnvironment( |
| 173 | this, |
| 174 | noNewArrows, |
| 175 | allowInsertArrow, |
| 176 | allowInsertArrowWithRest, |
| 177 | ); |
| 178 | |
| 179 | // @ts-expect-error TS requires explicit fn type annotation |
| 180 | fn.ensureBlock(); |
| 181 | setType(fn, "FunctionExpression"); |
| 182 | |
| 183 | if (!noNewArrows) { |
| 184 | const checkBinding = thisBinding |
| 185 | ? null |
| 186 | : fn.scope.generateUidIdentifier("arrowCheckId"); |
| 187 | if (checkBinding) { |
| 188 | fn.parentPath.scope.push({ |
| 189 | id: checkBinding, |
| 190 | init: objectExpression([]), |
| 191 | }); |
| 192 | } |
| 193 | |
| 194 | fn.get("body").unshiftContainer( |
| 195 | "body", |
| 196 | expressionStatement( |
| 197 | callExpression(this.hub.addHelper("newArrowCheck"), [ |
| 198 | thisExpression(), |
| 199 | checkBinding |
| 200 | ? identifier(checkBinding.name) |
| 201 | : identifier(thisBinding), |
| 202 | ]), |
| 203 | ), |
| 204 | ); |
| 205 | |
| 206 | fn.replaceWith( |
| 207 | callExpression( |
| 208 | memberExpression( |
| 209 | // @ts-expect-error TS can't infer nameFunction returns CallExpression | ArrowFunctionExpression here |
| 210 | nameFunction(this, true) || fn.node, |
| 211 | identifier("bind"), |
| 212 | ), |
| 213 | [checkBinding ? identifier(checkBinding.name) : thisExpression()], |
| 214 | ), |
| 215 | ); |
| 216 | |
| 217 | return fn.get("callee.object"); |
| 218 | } |
| 219 | |
| 220 | return fn; |
| 221 | } |
| 222 | |
| 223 | const getSuperCallsVisitor = mergeVisitors<{ |
| 224 | allSuperCalls: NodePath<t.CallExpression>[]; |
| 225 | }>([ |
| 226 | { |
| 227 | CallExpression(child, { allSuperCalls }) { |
| 228 | if (!child.get("callee").isSuper()) return; |
| 229 | allSuperCalls.push(child); |
| 230 | }, |
| 231 | }, |
| 232 | environmentVisitor, |
| 233 | ]); |
| 234 | |
| 235 | /** |
| 236 | * Given a function, traverse its contents, and if there are references to "this", "arguments", "super", |
| 237 | * or "new.target", ensure that these references reference the parent environment around this function. |
| 238 | * |
| 239 | * @returns `thisBinding`: the name of the injected reference to `this`; for example "_this" |
| 240 | * @returns `fnPath`: the new path to the function node. This is different from the fnPath |
| 241 | * parameter when the function node is wrapped in another node. |
| 242 | */ |
| 243 | function hoistFunctionEnvironment( |
| 244 | fnPath: NodePath<t.Function>, |
| 245 | // TODO(Babel 8): Consider defaulting to `false` for spec compliancy |
| 246 | noNewArrows: boolean | void = true, |
| 247 | allowInsertArrow: boolean | void = true, |
| 248 | allowInsertArrowWithRest: boolean | void = true, |
| 249 | ): { thisBinding: string; fnPath: NodePath<t.Function> } { |
| 250 | let arrowParent; |
| 251 | let thisEnvFn: NodePath<t.Function> = fnPath.findParent(p => { |
| 252 | if (p.isArrowFunctionExpression()) { |
| 253 | arrowParent ??= p; |
| 254 | return false; |
| 255 | } |
| 256 | return ( |
| 257 | p.isFunction() || |
| 258 | p.isProgram() || |
| 259 | p.isClassProperty({ static: false }) || |
| 260 | p.isClassPrivateProperty({ static: false }) |
| 261 | ); |
| 262 | }) as NodePath<t.Function>; |
| 263 | const inConstructor = thisEnvFn.isClassMethod({ kind: "constructor" }); |
| 264 | |
| 265 | if (thisEnvFn.isClassProperty() || thisEnvFn.isClassPrivateProperty()) { |
| 266 | if (arrowParent) { |
| 267 | thisEnvFn = arrowParent; |
| 268 | } else if (allowInsertArrow) { |
| 269 | // It's safe to wrap this function in another and not hoist to the |
| 270 | // top level because the 'this' binding is constant in class |
| 271 | // properties (since 'super()' has already been called), so we don't |
| 272 | // need to capture/reassign it at the top level. |
| 273 | fnPath.replaceWith( |
| 274 | callExpression( |
| 275 | arrowFunctionExpression([], toExpression(fnPath.node)), |
| 276 | [], |
| 277 | ), |
| 278 | ); |
| 279 | thisEnvFn = fnPath.get("callee") as NodePath<t.ArrowFunctionExpression>; |
| 280 | fnPath = thisEnvFn.get("body") as NodePath<t.FunctionExpression>; |
| 281 | } else { |
| 282 | throw fnPath.buildCodeFrameError( |
| 283 | "Unable to transform arrow inside class property", |
| 284 | ); |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | const { thisPaths, argumentsPaths, newTargetPaths, superProps, superCalls } = |
| 289 | getScopeInformation(fnPath); |
| 290 | |
| 291 | // Convert all super() calls in the constructor, if super is used in an arrow. |
| 292 | if (inConstructor && superCalls.length > 0) { |
| 293 | if (!allowInsertArrow) { |
| 294 | throw superCalls[0].buildCodeFrameError( |
| 295 | "When using '@babel/plugin-transform-arrow-functions', " + |
| 296 | "it's not possible to compile `super()` in an arrow function without compiling classes.\n" + |
| 297 | "Please add '@babel/plugin-transform-classes' to your Babel configuration.", |
| 298 | ); |
| 299 | } |
| 300 | if (!allowInsertArrowWithRest) { |
| 301 | // preset-env with target `since 2017` enables `transform-parameters` without `transform-classes`. |
| 302 | throw superCalls[0].buildCodeFrameError( |
| 303 | "When using '@babel/plugin-transform-parameters', " + |
| 304 | "it's not possible to compile `super()` in an arrow function with default or rest parameters without compiling classes.\n" + |
| 305 | "Please add '@babel/plugin-transform-classes' to your Babel configuration.", |
| 306 | ); |
| 307 | } |
| 308 | const allSuperCalls: NodePath<t.CallExpression>[] = []; |
| 309 | thisEnvFn.traverse(getSuperCallsVisitor, { allSuperCalls }); |
| 310 | const superBinding = getSuperBinding(thisEnvFn); |
| 311 | allSuperCalls.forEach(superCall => { |
| 312 | const callee = identifier(superBinding); |
| 313 | callee.loc = superCall.node.callee.loc; |
| 314 | |
| 315 | superCall.get("callee").replaceWith(callee); |
| 316 | }); |
| 317 | } |
| 318 | |
| 319 | // Convert all "arguments" references in the arrow to point at the alias. |
| 320 | if (argumentsPaths.length > 0) { |
| 321 | const argumentsBinding = getBinding(thisEnvFn, "arguments", () => { |
| 322 | const args = () => identifier("arguments"); |
| 323 | if (thisEnvFn.scope.path.isProgram()) { |
| 324 | return conditionalExpression( |
| 325 | binaryExpression( |
| 326 | "===", |
| 327 | unaryExpression("typeof", args()), |
| 328 | stringLiteral("undefined"), |
| 329 | ), |
| 330 | thisEnvFn.scope.buildUndefinedNode(), |
| 331 | args(), |
| 332 | ); |
| 333 | } else { |
| 334 | return args(); |
| 335 | } |
| 336 | }); |
| 337 | |
| 338 | argumentsPaths.forEach(argumentsChild => { |
| 339 | const argsRef = identifier(argumentsBinding); |
| 340 | argsRef.loc = argumentsChild.node.loc; |
| 341 | |
| 342 | argumentsChild.replaceWith(argsRef); |
| 343 | }); |
| 344 | } |
| 345 | |
| 346 | // Convert all "new.target" references in the arrow to point at the alias. |
| 347 | if (newTargetPaths.length > 0) { |
| 348 | const newTargetBinding = getBinding(thisEnvFn, "newtarget", () => |
| 349 | metaProperty(identifier("new"), identifier("target")), |
| 350 | ); |
| 351 | |
| 352 | newTargetPaths.forEach(targetChild => { |
| 353 | const targetRef = identifier(newTargetBinding); |
| 354 | targetRef.loc = targetChild.node.loc; |
| 355 | |
| 356 | targetChild.replaceWith(targetRef); |
| 357 | }); |
| 358 | } |
| 359 | |
| 360 | // Convert all "super.prop" references to point at aliases. |
| 361 | if (superProps.length > 0) { |
| 362 | if (!allowInsertArrow) { |
| 363 | throw superProps[0].buildCodeFrameError( |
| 364 | "When using '@babel/plugin-transform-arrow-functions', " + |
| 365 | "it's not possible to compile `super.prop` in an arrow function without compiling classes.\n" + |
| 366 | "Please add '@babel/plugin-transform-classes' to your Babel configuration.", |
| 367 | ); |
| 368 | } |
| 369 | |
| 370 | const flatSuperProps: NodePath<t.MemberExpression>[] = superProps.reduce( |
| 371 | (acc, superProp) => acc.concat(standardizeSuperProperty(superProp)), |
| 372 | [], |
| 373 | ); |
| 374 | |
| 375 | flatSuperProps.forEach(superProp => { |
| 376 | const key = superProp.node.computed |
| 377 | ? "" |
| 378 | : // @ts-expect-error super property must not contain private name |
| 379 | superProp.get("property").node.name; |
| 380 | |
| 381 | const superParentPath = superProp.parentPath; |
| 382 | |
| 383 | const isAssignment = superParentPath.isAssignmentExpression({ |
| 384 | left: superProp.node, |
| 385 | }); |
| 386 | const isCall = superParentPath.isCallExpression({ |
| 387 | callee: superProp.node, |
| 388 | }); |
| 389 | const isTaggedTemplate = superParentPath.isTaggedTemplateExpression({ |
| 390 | tag: superProp.node, |
| 391 | }); |
| 392 | const superBinding = getSuperPropBinding(thisEnvFn, isAssignment, key); |
| 393 | |
| 394 | const args: t.Expression[] = []; |
| 395 | if (superProp.node.computed) { |
| 396 | // SuperProperty must not be a private name |
| 397 | args.push(superProp.get("property").node as t.Expression); |
| 398 | } |
| 399 | |
| 400 | if (isAssignment) { |
| 401 | const value = superParentPath.node.right; |
| 402 | args.push(value); |
| 403 | } |
| 404 | |
| 405 | const call = callExpression(identifier(superBinding), args); |
| 406 | |
| 407 | if (isCall) { |
| 408 | superParentPath.unshiftContainer("arguments", thisExpression()); |
| 409 | superProp.replaceWith(memberExpression(call, identifier("call"))); |
| 410 | |
| 411 | thisPaths.push( |
| 412 | superParentPath.get("arguments.0") as NodePath<t.ThisExpression>, |
| 413 | ); |
| 414 | } else if (isAssignment) { |
| 415 | // Replace not only the super.prop, but the whole assignment |
| 416 | superParentPath.replaceWith(call); |
| 417 | } else if (isTaggedTemplate) { |
| 418 | superProp.replaceWith( |
| 419 | callExpression(memberExpression(call, identifier("bind"), false), [ |
| 420 | thisExpression(), |
| 421 | ]), |
| 422 | ); |
| 423 | |
| 424 | thisPaths.push( |
| 425 | superProp.get("arguments.0") as NodePath<t.ThisExpression>, |
| 426 | ); |
| 427 | } else { |
| 428 | superProp.replaceWith(call); |
| 429 | } |
| 430 | }); |
| 431 | } |
| 432 | |
| 433 | // Convert all "this" references in the arrow to point at the alias. |
| 434 | let thisBinding: string | null; |
| 435 | if (thisPaths.length > 0 || !noNewArrows) { |
| 436 | thisBinding = getThisBinding(thisEnvFn, inConstructor); |
| 437 | |
| 438 | if ( |
| 439 | noNewArrows || |
| 440 | // In subclass constructors, still need to rewrite because "this" can't be bound in spec mode |
| 441 | // because it might not have been initialized yet. |
| 442 | (inConstructor && hasSuperClass(thisEnvFn)) |
| 443 | ) { |
| 444 | thisPaths.forEach(thisChild => { |
| 445 | const thisRef = thisChild.isJSX() |
| 446 | ? jsxIdentifier(thisBinding) |
| 447 | : identifier(thisBinding); |
| 448 | |
| 449 | thisRef.loc = thisChild.node.loc; |
| 450 | thisChild.replaceWith(thisRef); |
| 451 | }); |
| 452 | |
| 453 | if (!noNewArrows) thisBinding = null; |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | return { thisBinding, fnPath }; |
| 458 | } |
| 459 | |
| 460 | type LogicalOp = Parameters<typeof logicalExpression>[0]; |
| 461 | type BinaryOp = Parameters<typeof binaryExpression>[0]; |
| 462 | |
| 463 | function isLogicalOp(op: string): op is LogicalOp { |
| 464 | return LOGICAL_OPERATORS.includes(op); |
| 465 | } |
| 466 | |
| 467 | function standardizeSuperProperty( |
| 468 | superProp: NodePath<t.MemberExpression>, |
| 469 | ): |
| 470 | | [NodePath<t.MemberExpression>] |
| 471 | | [NodePath<t.MemberExpression>, NodePath<t.MemberExpression>] { |
| 472 | if ( |
| 473 | superProp.parentPath.isAssignmentExpression() && |
| 474 | superProp.parentPath.node.operator !== "=" |
| 475 | ) { |
| 476 | const assignmentPath = superProp.parentPath; |
| 477 | |
| 478 | const op = assignmentPath.node.operator.slice(0, -1) as |
| 479 | | LogicalOp |
| 480 | | BinaryOp; |
| 481 | |
| 482 | const value = assignmentPath.node.right; |
| 483 | |
| 484 | const isLogicalAssignment = isLogicalOp(op); |
| 485 | |
| 486 | if (superProp.node.computed) { |
| 487 | // from: super[foo] **= 4; |
| 488 | // to: super[tmp = foo] = super[tmp] ** 4; |
| 489 | |
| 490 | // from: super[foo] ??= 4; |
| 491 | // to: super[tmp = foo] ?? super[tmp] = 4; |
| 492 | |
| 493 | const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp"); |
| 494 | |
| 495 | const object = superProp.node.object; |
| 496 | const property = superProp.node.property as t.Expression; |
| 497 | |
| 498 | assignmentPath |
| 499 | .get("left") |
| 500 | .replaceWith( |
| 501 | memberExpression( |
| 502 | object, |
| 503 | assignmentExpression("=", tmp, property), |
| 504 | true /* computed */, |
| 505 | ), |
| 506 | ); |
| 507 | |
| 508 | assignmentPath |
| 509 | .get("right") |
| 510 | .replaceWith( |
| 511 | rightExpression( |
| 512 | isLogicalAssignment ? "=" : op, |
| 513 | memberExpression(object, identifier(tmp.name), true /* computed */), |
| 514 | value, |
| 515 | ), |
| 516 | ); |
| 517 | } else { |
| 518 | // from: super.foo **= 4; |
| 519 | // to: super.foo = super.foo ** 4; |
| 520 | |
| 521 | // from: super.foo ??= 4; |
| 522 | // to: super.foo ?? super.foo = 4; |
| 523 | |
| 524 | const object = superProp.node.object; |
| 525 | const property = superProp.node.property as t.Identifier; |
| 526 | |
| 527 | assignmentPath |
| 528 | .get("left") |
| 529 | .replaceWith(memberExpression(object, property)); |
| 530 | |
| 531 | assignmentPath |
| 532 | .get("right") |
| 533 | .replaceWith( |
| 534 | rightExpression( |
| 535 | isLogicalAssignment ? "=" : op, |
| 536 | memberExpression(object, identifier(property.name)), |
| 537 | value, |
| 538 | ), |
| 539 | ); |
| 540 | } |
| 541 | |
| 542 | if (isLogicalAssignment) { |
| 543 | assignmentPath.replaceWith( |
| 544 | logicalExpression( |
| 545 | op, |
| 546 | assignmentPath.node.left as t.MemberExpression, |
| 547 | assignmentPath.node.right, |
| 548 | ), |
| 549 | ); |
| 550 | } else { |
| 551 | assignmentPath.node.operator = "="; |
| 552 | } |
| 553 | |
| 554 | return [ |
| 555 | assignmentPath.get("left") as NodePath<t.MemberExpression>, |
| 556 | assignmentPath.get("right").get("left"), |
| 557 | ]; |
| 558 | } else if (superProp.parentPath.isUpdateExpression()) { |
| 559 | const updateExpr = superProp.parentPath; |
| 560 | |
| 561 | const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp"); |
| 562 | const computedKey = superProp.node.computed |
| 563 | ? superProp.scope.generateDeclaredUidIdentifier("prop") |
| 564 | : null; |
| 565 | |
| 566 | const parts: t.Expression[] = [ |
| 567 | assignmentExpression( |
| 568 | "=", |
| 569 | tmp, |
| 570 | memberExpression( |
| 571 | superProp.node.object, |
| 572 | computedKey |
| 573 | ? assignmentExpression( |
| 574 | "=", |
| 575 | computedKey, |
| 576 | superProp.node.property as t.Expression, |
| 577 | ) |
| 578 | : superProp.node.property, |
| 579 | superProp.node.computed, |
| 580 | ), |
| 581 | ), |
| 582 | assignmentExpression( |
| 583 | "=", |
| 584 | memberExpression( |
| 585 | superProp.node.object, |
| 586 | computedKey ? identifier(computedKey.name) : superProp.node.property, |
| 587 | superProp.node.computed, |
| 588 | ), |
| 589 | binaryExpression( |
| 590 | // map `++` to `+`, and `--` to `-` |
| 591 | superProp.parentPath.node.operator[0] as "+" | "-", |
| 592 | identifier(tmp.name), |
| 593 | numericLiteral(1), |
| 594 | ), |
| 595 | ), |
| 596 | ]; |
| 597 | |
| 598 | if (!superProp.parentPath.node.prefix) { |
| 599 | parts.push(identifier(tmp.name)); |
| 600 | } |
| 601 | |
| 602 | updateExpr.replaceWith(sequenceExpression(parts)); |
| 603 | |
| 604 | const left = updateExpr.get( |
| 605 | "expressions.0.right", |
| 606 | ) as NodePath<t.MemberExpression>; |
| 607 | const right = updateExpr.get( |
| 608 | "expressions.1.left", |
| 609 | ) as NodePath<t.MemberExpression>; |
| 610 | return [left, right]; |
| 611 | } |
| 612 | |
| 613 | return [superProp]; |
| 614 | |
| 615 | function rightExpression( |
| 616 | op: BinaryOp | "=", |
| 617 | left: t.MemberExpression, |
| 618 | right: t.Expression, |
| 619 | ) { |
| 620 | if (op === "=") { |
| 621 | return assignmentExpression("=", left, right); |
| 622 | } else { |
| 623 | return binaryExpression(op, left, right); |
| 624 | } |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | function hasSuperClass(thisEnvFn: NodePath<t.Function>) { |
| 629 | return ( |
| 630 | thisEnvFn.isClassMethod() && |
| 631 | !!(thisEnvFn.parentPath.parentPath.node as t.Class).superClass |
| 632 | ); |
| 633 | } |
| 634 | |
| 635 | const assignSuperThisVisitor = mergeVisitors<{ |
| 636 | supers: WeakSet<t.CallExpression>; |
| 637 | thisBinding: string; |
| 638 | }>([ |
| 639 | { |
| 640 | CallExpression(child, { supers, thisBinding }) { |
| 641 | if (!child.get("callee").isSuper()) return; |
| 642 | if (supers.has(child.node)) return; |
| 643 | supers.add(child.node); |
| 644 | |
| 645 | child.replaceWithMultiple([ |
| 646 | child.node, |
| 647 | assignmentExpression("=", identifier(thisBinding), identifier("this")), |
| 648 | ]); |
| 649 | }, |
| 650 | }, |
| 651 | environmentVisitor, |
| 652 | ]); |
| 653 | |
| 654 | // Create a binding that evaluates to the "this" of the given function. |
| 655 | function getThisBinding( |
| 656 | thisEnvFn: NodePath<t.Function>, |
| 657 | inConstructor: boolean, |
| 658 | ) { |
| 659 | return getBinding(thisEnvFn, "this", thisBinding => { |
| 660 | if (!inConstructor || !hasSuperClass(thisEnvFn)) return thisExpression(); |
| 661 | |
| 662 | thisEnvFn.traverse(assignSuperThisVisitor, { |
| 663 | supers: new WeakSet(), |
| 664 | thisBinding, |
| 665 | }); |
| 666 | }); |
| 667 | } |
| 668 | |
| 669 | // Create a binding for a function that will call "super()" with arguments passed through. |
| 670 | function getSuperBinding(thisEnvFn: NodePath<t.Function>) { |
| 671 | return getBinding(thisEnvFn, "supercall", () => { |
| 672 | const argsBinding = thisEnvFn.scope.generateUidIdentifier("args"); |
| 673 | return arrowFunctionExpression( |
| 674 | [restElement(argsBinding)], |
| 675 | callExpression(_super(), [spreadElement(identifier(argsBinding.name))]), |
| 676 | ); |
| 677 | }); |
| 678 | } |
| 679 | |
| 680 | // Create a binding for a function that will call "super.foo" or "super[foo]". |
| 681 | function getSuperPropBinding( |
| 682 | thisEnvFn: NodePath<t.Function>, |
| 683 | isAssignment: boolean, |
| 684 | propName: string, |
| 685 | ) { |
| 686 | const op = isAssignment ? "set" : "get"; |
| 687 | |
| 688 | return getBinding(thisEnvFn, `superprop_${op}:${propName || ""}`, () => { |
| 689 | const argsList = []; |
| 690 | |
| 691 | let fnBody; |
| 692 | if (propName) { |
| 693 | // () => super.foo |
| 694 | fnBody = memberExpression(_super(), identifier(propName)); |
| 695 | } else { |
| 696 | const method = thisEnvFn.scope.generateUidIdentifier("prop"); |
| 697 | // (method) => super[method] |
| 698 | argsList.unshift(method); |
| 699 | fnBody = memberExpression( |
| 700 | _super(), |
| 701 | identifier(method.name), |
| 702 | true /* computed */, |
| 703 | ); |
| 704 | } |
| 705 | |
| 706 | if (isAssignment) { |
| 707 | const valueIdent = thisEnvFn.scope.generateUidIdentifier("value"); |
| 708 | argsList.push(valueIdent); |
| 709 | |
| 710 | fnBody = assignmentExpression("=", fnBody, identifier(valueIdent.name)); |
| 711 | } |
| 712 | |
| 713 | return arrowFunctionExpression(argsList, fnBody); |
| 714 | }); |
| 715 | } |
| 716 | |
| 717 | function getBinding( |
| 718 | thisEnvFn: NodePath, |
| 719 | key: string, |
| 720 | init: (name: string) => t.Expression, |
| 721 | ) { |
| 722 | const cacheKey = "binding:" + key; |
| 723 | let data: string | undefined = thisEnvFn.getData(cacheKey); |
| 724 | if (!data) { |
| 725 | const id = thisEnvFn.scope.generateUidIdentifier(key); |
| 726 | data = id.name; |
| 727 | thisEnvFn.setData(cacheKey, data); |
| 728 | |
| 729 | thisEnvFn.scope.push({ |
| 730 | id: id, |
| 731 | init: init(data), |
| 732 | }); |
| 733 | } |
| 734 | |
| 735 | return data; |
| 736 | } |
| 737 | |
| 738 | type ScopeInfo = { |
| 739 | thisPaths: NodePath<t.ThisExpression | t.JSXIdentifier>[]; |
| 740 | superCalls: NodePath<t.CallExpression>[]; |
| 741 | superProps: NodePath<t.MemberExpression>[]; |
| 742 | argumentsPaths: NodePath<t.Identifier | t.JSXIdentifier>[]; |
| 743 | newTargetPaths: NodePath<t.MetaProperty>[]; |
| 744 | }; |
| 745 | |
| 746 | const getScopeInformationVisitor = mergeVisitors<ScopeInfo>([ |
| 747 | { |
| 748 | ThisExpression(child, { thisPaths }) { |
| 749 | thisPaths.push(child); |
| 750 | }, |
| 751 | JSXIdentifier(child, { thisPaths }) { |
| 752 | if (child.node.name !== "this") return; |
| 753 | if ( |
| 754 | !child.parentPath.isJSXMemberExpression({ object: child.node }) && |
| 755 | !child.parentPath.isJSXOpeningElement({ name: child.node }) |
| 756 | ) { |
| 757 | return; |
| 758 | } |
| 759 | |
| 760 | thisPaths.push(child); |
| 761 | }, |
| 762 | CallExpression(child, { superCalls }) { |
| 763 | if (child.get("callee").isSuper()) superCalls.push(child); |
| 764 | }, |
| 765 | MemberExpression(child, { superProps }) { |
| 766 | if (child.get("object").isSuper()) superProps.push(child); |
| 767 | }, |
| 768 | Identifier(child, { argumentsPaths }) { |
| 769 | if (!child.isReferencedIdentifier({ name: "arguments" })) return; |
| 770 | |
| 771 | let curr = child.scope; |
| 772 | do { |
| 773 | if (curr.hasOwnBinding("arguments")) { |
| 774 | curr.rename("arguments"); |
| 775 | return; |
| 776 | } |
| 777 | if (curr.path.isFunction() && !curr.path.isArrowFunctionExpression()) { |
| 778 | break; |
| 779 | } |
| 780 | } while ((curr = curr.parent)); |
| 781 | |
| 782 | argumentsPaths.push(child); |
| 783 | }, |
| 784 | MetaProperty(child, { newTargetPaths }) { |
| 785 | if (!child.get("meta").isIdentifier({ name: "new" })) return; |
| 786 | if (!child.get("property").isIdentifier({ name: "target" })) return; |
| 787 | |
| 788 | newTargetPaths.push(child); |
| 789 | }, |
| 790 | }, |
| 791 | environmentVisitor, |
| 792 | ]); |
| 793 | |
| 794 | function getScopeInformation(fnPath: NodePath) { |
| 795 | const thisPaths: ScopeInfo["thisPaths"] = []; |
| 796 | const argumentsPaths: ScopeInfo["argumentsPaths"] = []; |
| 797 | const newTargetPaths: ScopeInfo["newTargetPaths"] = []; |
| 798 | const superProps: ScopeInfo["superProps"] = []; |
| 799 | const superCalls: ScopeInfo["superCalls"] = []; |
| 800 | |
| 801 | fnPath.traverse(getScopeInformationVisitor, { |
| 802 | thisPaths, |
| 803 | argumentsPaths, |
| 804 | newTargetPaths, |
| 805 | superProps, |
| 806 | superCalls, |
| 807 | }); |
| 808 | |
| 809 | return { |
| 810 | thisPaths, |
| 811 | argumentsPaths, |
| 812 | newTargetPaths, |
| 813 | superProps, |
| 814 | superCalls, |
| 815 | }; |
| 816 | } |