| 1 | // This file contains methods responsible for replacing a node with another. |
| 2 | |
| 3 | import { codeFrameColumns } from "@babel/code-frame"; |
| 4 | import traverse from "../index"; |
| 5 | import NodePath from "./index"; |
| 6 | import { path as pathCache } from "../cache"; |
| 7 | import { parse } from "@babel/parser"; |
| 8 | import { |
| 9 | FUNCTION_TYPES, |
| 10 | arrowFunctionExpression, |
| 11 | assignmentExpression, |
| 12 | awaitExpression, |
| 13 | blockStatement, |
| 14 | callExpression, |
| 15 | cloneNode, |
| 16 | expressionStatement, |
| 17 | identifier, |
| 18 | inheritLeadingComments, |
| 19 | inheritTrailingComments, |
| 20 | inheritsComments, |
| 21 | isExpression, |
| 22 | isProgram, |
| 23 | isStatement, |
| 24 | removeComments, |
| 25 | returnStatement, |
| 26 | toSequenceExpression, |
| 27 | validate, |
| 28 | yieldExpression, |
| 29 | } from "@babel/types"; |
| 30 | import type * as t from "@babel/types"; |
| 31 | import hoistVariables from "@babel/helper-hoist-variables"; |
| 32 | |
| 33 | /** |
| 34 | * Replace a node with an array of multiple. This method performs the following steps: |
| 35 | * |
| 36 | * - Inherit the comments of first provided node with that of the current node. |
| 37 | * - Insert the provided nodes after the current node. |
| 38 | * - Remove the current node. |
| 39 | */ |
| 40 | |
| 41 | export function replaceWithMultiple( |
| 42 | this: NodePath, |
| 43 | nodes: t.Node | t.Node[], |
| 44 | ): NodePath[] { |
| 45 | this.resync(); |
| 46 | |
| 47 | nodes = this._verifyNodeList(nodes); |
| 48 | inheritLeadingComments(nodes[0], this.node); |
| 49 | inheritTrailingComments(nodes[nodes.length - 1], this.node); |
| 50 | pathCache.get(this.parent)?.delete(this.node); |
| 51 | this.node = |
| 52 | // @ts-expect-error this.key must present in this.container |
| 53 | this.container[this.key] = null; |
| 54 | const paths = this.insertAfter(nodes); |
| 55 | |
| 56 | if (this.node) { |
| 57 | this.requeue(); |
| 58 | } else { |
| 59 | this.remove(); |
| 60 | } |
| 61 | return paths; |
| 62 | } |
| 63 | |
| 64 | /** |
| 65 | * Parse a string as an expression and replace the current node with the result. |
| 66 | * |
| 67 | * NOTE: This is typically not a good idea to use. Building source strings when |
| 68 | * transforming ASTs is an antipattern and SHOULD NOT be encouraged. Even if it's |
| 69 | * easier to use, your transforms will be extremely brittle. |
| 70 | */ |
| 71 | |
| 72 | export function replaceWithSourceString(this: NodePath, replacement: string) { |
| 73 | this.resync(); |
| 74 | let ast: t.File; |
| 75 | |
| 76 | try { |
| 77 | replacement = `(${replacement})`; |
| 78 | // @ts-expect-error todo: use babel-types ast typings in Babel parser |
| 79 | ast = parse(replacement); |
| 80 | } catch (err) { |
| 81 | const loc = err.loc; |
| 82 | if (loc) { |
| 83 | err.message += |
| 84 | " - make sure this is an expression.\n" + |
| 85 | codeFrameColumns(replacement, { |
| 86 | start: { |
| 87 | line: loc.line, |
| 88 | column: loc.column + 1, |
| 89 | }, |
| 90 | }); |
| 91 | err.code = "BABEL_REPLACE_SOURCE_ERROR"; |
| 92 | } |
| 93 | throw err; |
| 94 | } |
| 95 | |
| 96 | const expressionAST = (ast.program.body[0] as t.ExpressionStatement) |
| 97 | .expression; |
| 98 | traverse.removeProperties(expressionAST); |
| 99 | return this.replaceWith(expressionAST); |
| 100 | } |
| 101 | |
| 102 | /** |
| 103 | * Replace the current node with another. |
| 104 | */ |
| 105 | |
| 106 | export function replaceWith<R extends t.Node>( |
| 107 | this: NodePath, |
| 108 | replacementPath: R | NodePath<R>, |
| 109 | ): [NodePath<R>] { |
| 110 | this.resync(); |
| 111 | |
| 112 | if (this.removed) { |
| 113 | throw new Error("You can't replace this node, we've already removed it"); |
| 114 | } |
| 115 | |
| 116 | let replacement: t.Node = |
| 117 | replacementPath instanceof NodePath |
| 118 | ? replacementPath.node |
| 119 | : replacementPath; |
| 120 | |
| 121 | if (!replacement) { |
| 122 | throw new Error( |
| 123 | "You passed `path.replaceWith()` a falsy node, use `path.remove()` instead", |
| 124 | ); |
| 125 | } |
| 126 | |
| 127 | if (this.node === replacement) { |
| 128 | return [this as NodePath<R>]; |
| 129 | } |
| 130 | |
| 131 | if (this.isProgram() && !isProgram(replacement)) { |
| 132 | throw new Error( |
| 133 | "You can only replace a Program root node with another Program node", |
| 134 | ); |
| 135 | } |
| 136 | |
| 137 | if (Array.isArray(replacement)) { |
| 138 | throw new Error( |
| 139 | "Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`", |
| 140 | ); |
| 141 | } |
| 142 | |
| 143 | if (typeof replacement === "string") { |
| 144 | throw new Error( |
| 145 | "Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`", |
| 146 | ); |
| 147 | } |
| 148 | |
| 149 | let nodePath = ""; |
| 150 | |
| 151 | if (this.isNodeType("Statement") && isExpression(replacement)) { |
| 152 | if ( |
| 153 | !this.canHaveVariableDeclarationOrExpression() && |
| 154 | !this.canSwapBetweenExpressionAndStatement(replacement) && |
| 155 | !this.parentPath.isExportDefaultDeclaration() |
| 156 | ) { |
| 157 | // replacing a statement with an expression so wrap it in an expression statement |
| 158 | replacement = expressionStatement(replacement); |
| 159 | nodePath = "expression"; |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | if (this.isNodeType("Expression") && isStatement(replacement)) { |
| 164 | if ( |
| 165 | !this.canHaveVariableDeclarationOrExpression() && |
| 166 | !this.canSwapBetweenExpressionAndStatement(replacement) |
| 167 | ) { |
| 168 | // replacing an expression with a statement so let's explode it |
| 169 | return this.replaceExpressionWithStatements([replacement]) as [ |
| 170 | NodePath<R>, |
| 171 | ]; |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | const oldNode = this.node; |
| 176 | if (oldNode) { |
| 177 | inheritsComments(replacement, oldNode); |
| 178 | removeComments(oldNode); |
| 179 | } |
| 180 | |
| 181 | // replace the node |
| 182 | this._replaceWith(replacement); |
| 183 | this.type = replacement.type; |
| 184 | |
| 185 | // potentially create new scope |
| 186 | this.setScope(); |
| 187 | |
| 188 | // requeue for visiting |
| 189 | this.requeue(); |
| 190 | |
| 191 | return [ |
| 192 | nodePath ? (this.get(nodePath) as NodePath<R>) : (this as NodePath<R>), |
| 193 | ]; |
| 194 | } |
| 195 | |
| 196 | /** |
| 197 | * Description |
| 198 | */ |
| 199 | |
| 200 | export function _replaceWith(this: NodePath, node: t.Node) { |
| 201 | if (!this.container) { |
| 202 | throw new ReferenceError("Container is falsy"); |
| 203 | } |
| 204 | |
| 205 | if (this.inList) { |
| 206 | // @ts-expect-error todo(flow->ts): check if validate accepts a numeric key |
| 207 | validate(this.parent, this.key, [node]); |
| 208 | } else { |
| 209 | validate(this.parent, this.key as string, node); |
| 210 | } |
| 211 | |
| 212 | this.debug(`Replace with ${node?.type}`); |
| 213 | pathCache.get(this.parent)?.set(node, this).delete(this.node); |
| 214 | |
| 215 | this.node = |
| 216 | // @ts-expect-error this.key must present in this.container |
| 217 | this.container[this.key] = node; |
| 218 | } |
| 219 | |
| 220 | /** |
| 221 | * This method takes an array of statements nodes and then explodes it |
| 222 | * into expressions. This method retains completion records which is |
| 223 | * extremely important to retain original semantics. |
| 224 | */ |
| 225 | |
| 226 | export function replaceExpressionWithStatements( |
| 227 | this: NodePath, |
| 228 | nodes: Array<t.Statement>, |
| 229 | ) { |
| 230 | this.resync(); |
| 231 | |
| 232 | const nodesAsSequenceExpression = toSequenceExpression(nodes, this.scope); |
| 233 | |
| 234 | if (nodesAsSequenceExpression) { |
| 235 | return this.replaceWith(nodesAsSequenceExpression)[0].get("expressions"); |
| 236 | } |
| 237 | |
| 238 | const functionParent = this.getFunctionParent(); |
| 239 | const isParentAsync = functionParent?.is("async"); |
| 240 | const isParentGenerator = functionParent?.is("generator"); |
| 241 | |
| 242 | const container = arrowFunctionExpression([], blockStatement(nodes)); |
| 243 | |
| 244 | this.replaceWith(callExpression(container, [])); |
| 245 | // replaceWith changes the type of "this", but it isn't trackable by TS |
| 246 | type ThisType = NodePath< |
| 247 | t.CallExpression & { |
| 248 | callee: t.ArrowFunctionExpression & { body: t.BlockStatement }; |
| 249 | } |
| 250 | >; |
| 251 | |
| 252 | // hoist variable declaration in do block |
| 253 | // `(do { var x = 1; x;})` -> `var x; (() => { x = 1; return x; })()` |
| 254 | const callee = (this as ThisType).get("callee"); |
| 255 | hoistVariables( |
| 256 | callee.get("body"), |
| 257 | (id: t.Identifier) => { |
| 258 | this.scope.push({ id }); |
| 259 | }, |
| 260 | "var", |
| 261 | ); |
| 262 | |
| 263 | // add implicit returns to all ending expression statements |
| 264 | const completionRecords: Array<NodePath> = (this as ThisType) |
| 265 | .get("callee") |
| 266 | .getCompletionRecords(); |
| 267 | for (const path of completionRecords) { |
| 268 | if (!path.isExpressionStatement()) continue; |
| 269 | |
| 270 | const loop = path.findParent(path => path.isLoop()); |
| 271 | if (loop) { |
| 272 | let uid = loop.getData("expressionReplacementReturnUid"); |
| 273 | |
| 274 | if (!uid) { |
| 275 | uid = callee.scope.generateDeclaredUidIdentifier("ret"); |
| 276 | callee |
| 277 | .get("body") |
| 278 | .pushContainer("body", returnStatement(cloneNode(uid))); |
| 279 | loop.setData("expressionReplacementReturnUid", uid); |
| 280 | } else { |
| 281 | uid = identifier(uid.name); |
| 282 | } |
| 283 | |
| 284 | path |
| 285 | .get("expression") |
| 286 | .replaceWith( |
| 287 | assignmentExpression("=", cloneNode(uid), path.node.expression), |
| 288 | ); |
| 289 | } else { |
| 290 | path.replaceWith(returnStatement(path.node.expression)); |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | // This is an IIFE, so we don't need to worry about the noNewArrows assumption |
| 295 | callee.arrowFunctionToExpression(); |
| 296 | // Fixme: we can not `assert this is NodePath<t.FunctionExpression>` in `arrowFunctionToExpression` |
| 297 | // because it is not a class method known at compile time. |
| 298 | const newCallee = callee as unknown as NodePath<t.FunctionExpression>; |
| 299 | |
| 300 | // (() => await xxx)() -> await (async () => await xxx)(); |
| 301 | const needToAwaitFunction = |
| 302 | isParentAsync && |
| 303 | traverse.hasType( |
| 304 | (this.get("callee.body") as NodePath<t.BlockStatement>).node, |
| 305 | "AwaitExpression", |
| 306 | FUNCTION_TYPES, |
| 307 | ); |
| 308 | const needToYieldFunction = |
| 309 | isParentGenerator && |
| 310 | traverse.hasType( |
| 311 | (this.get("callee.body") as NodePath<t.BlockStatement>).node, |
| 312 | "YieldExpression", |
| 313 | FUNCTION_TYPES, |
| 314 | ); |
| 315 | if (needToAwaitFunction) { |
| 316 | newCallee.set("async", true); |
| 317 | // yield* will await the generator return result |
| 318 | if (!needToYieldFunction) { |
| 319 | this.replaceWith(awaitExpression((this as ThisType).node)); |
| 320 | } |
| 321 | } |
| 322 | if (needToYieldFunction) { |
| 323 | newCallee.set("generator", true); |
| 324 | this.replaceWith(yieldExpression((this as ThisType).node, true)); |
| 325 | } |
| 326 | |
| 327 | return newCallee.get("body.body"); |
| 328 | } |
| 329 | |
| 330 | export function replaceInline(this: NodePath, nodes: t.Node | Array<t.Node>) { |
| 331 | this.resync(); |
| 332 | |
| 333 | if (Array.isArray(nodes)) { |
| 334 | if (Array.isArray(this.container)) { |
| 335 | nodes = this._verifyNodeList(nodes); |
| 336 | const paths = this._containerInsertAfter(nodes); |
| 337 | this.remove(); |
| 338 | return paths; |
| 339 | } else { |
| 340 | return this.replaceWithMultiple(nodes); |
| 341 | } |
| 342 | } else { |
| 343 | return this.replaceWith(nodes); |
| 344 | } |
| 345 | } |