| 1 | // This file contains methods that modify the path/node in some ways. |
| 2 | |
| 3 | import { path as pathCache } from "../cache"; |
| 4 | import PathHoister from "./lib/hoister"; |
| 5 | import NodePath from "./index"; |
| 6 | import { |
| 7 | arrowFunctionExpression, |
| 8 | assertExpression, |
| 9 | assignmentExpression, |
| 10 | blockStatement, |
| 11 | callExpression, |
| 12 | cloneNode, |
| 13 | expressionStatement, |
| 14 | isAssignmentExpression, |
| 15 | isCallExpression, |
| 16 | isExportNamedDeclaration, |
| 17 | isExpression, |
| 18 | isIdentifier, |
| 19 | isSequenceExpression, |
| 20 | isSuper, |
| 21 | thisExpression, |
| 22 | } from "@babel/types"; |
| 23 | import type * as t from "@babel/types"; |
| 24 | import type Scope from "../scope"; |
| 25 | |
| 26 | /** |
| 27 | * Insert the provided nodes before the current one. |
| 28 | */ |
| 29 | |
| 30 | export function insertBefore( |
| 31 | this: NodePath, |
| 32 | nodes_: t.Node | t.Node[], |
| 33 | ): NodePath[] { |
| 34 | this._assertUnremoved(); |
| 35 | |
| 36 | const nodes = this._verifyNodeList(nodes_); |
| 37 | |
| 38 | const { parentPath, parent } = this; |
| 39 | |
| 40 | if ( |
| 41 | parentPath.isExpressionStatement() || |
| 42 | parentPath.isLabeledStatement() || |
| 43 | // https://github.com/babel/babel/issues/15293 |
| 44 | // When Babel transforms `export class String { field }`, the class properties plugin will inject the defineProperty |
| 45 | // helper, which depends on the builtins e.g. String, Number, Symbol, etc. To prevent them from being shadowed by local |
| 46 | // exports, the helper injector replaces the named export into `class _String { field }; export { _String as String }`, |
| 47 | // with `parentPath` here changed to the moved ClassDeclaration, causing rare inconsistency between `parent` and `parentPath`. |
| 48 | // Here we retrieve the parent type from the `parent` property. This is a temporary fix and we should revisit when |
| 49 | // helpers should get injected. |
| 50 | isExportNamedDeclaration(parent) || |
| 51 | (parentPath.isExportDefaultDeclaration() && this.isDeclaration()) |
| 52 | ) { |
| 53 | return parentPath.insertBefore(nodes); |
| 54 | } else if ( |
| 55 | (this.isNodeType("Expression") && !this.isJSXElement()) || |
| 56 | (parentPath.isForStatement() && this.key === "init") |
| 57 | ) { |
| 58 | if (this.node) nodes.push(this.node); |
| 59 | // @ts-expect-error todo(flow->ts): check that nodes is an array of statements |
| 60 | return this.replaceExpressionWithStatements(nodes); |
| 61 | } else if (Array.isArray(this.container)) { |
| 62 | return this._containerInsertBefore(nodes); |
| 63 | } else if (this.isStatementOrBlock()) { |
| 64 | const node = this.node as t.Statement; |
| 65 | const shouldInsertCurrentNode = |
| 66 | node && |
| 67 | (!this.isExpressionStatement() || |
| 68 | (node as t.ExpressionStatement).expression != null); |
| 69 | |
| 70 | this.replaceWith(blockStatement(shouldInsertCurrentNode ? [node] : [])); |
| 71 | return (this as NodePath<t.BlockStatement>).unshiftContainer( |
| 72 | "body", |
| 73 | // @ts-expect-error Fixme: refine nodes to t.BlockStatement["body"] when this is a BlockStatement path |
| 74 | nodes, |
| 75 | ); |
| 76 | } else { |
| 77 | throw new Error( |
| 78 | "We don't know what to do with this node type. " + |
| 79 | "We were previously a Statement but we can't fit in here?", |
| 80 | ); |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | export function _containerInsert<N extends t.Node>( |
| 85 | this: NodePath, |
| 86 | from: number, |
| 87 | nodes: N[], |
| 88 | ): NodePath<N>[] { |
| 89 | this.updateSiblingKeys(from, nodes.length); |
| 90 | |
| 91 | const paths: NodePath<N>[] = []; |
| 92 | |
| 93 | // @ts-expect-error todo(flow->ts): this.container could be a NodePath |
| 94 | this.container.splice(from, 0, ...nodes); |
| 95 | for (let i = 0; i < nodes.length; i++) { |
| 96 | const to = from + i; |
| 97 | const path = this.getSibling(to) as NodePath<N>; |
| 98 | paths.push(path); |
| 99 | |
| 100 | if (this.context && this.context.queue) { |
| 101 | path.pushContext(this.context); |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | const contexts = this._getQueueContexts(); |
| 106 | |
| 107 | for (const path of paths) { |
| 108 | path.setScope(); |
| 109 | path.debug("Inserted."); |
| 110 | |
| 111 | for (const context of contexts) { |
| 112 | context.maybeQueue(path, true); |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | return paths; |
| 117 | } |
| 118 | |
| 119 | export function _containerInsertBefore<N extends t.Node>( |
| 120 | this: NodePath, |
| 121 | nodes: N[], |
| 122 | ) { |
| 123 | return this._containerInsert(this.key as number, nodes); |
| 124 | } |
| 125 | |
| 126 | export function _containerInsertAfter<N extends t.Node>( |
| 127 | this: NodePath, |
| 128 | nodes: N[], |
| 129 | ) { |
| 130 | return this._containerInsert((this.key as number) + 1, nodes); |
| 131 | } |
| 132 | |
| 133 | const last = <T>(arr: T[]) => arr[arr.length - 1]; |
| 134 | |
| 135 | function isHiddenInSequenceExpression(path: NodePath): boolean { |
| 136 | return ( |
| 137 | isSequenceExpression(path.parent) && |
| 138 | (last(path.parent.expressions) !== path.node || |
| 139 | isHiddenInSequenceExpression(path.parentPath)) |
| 140 | ); |
| 141 | } |
| 142 | |
| 143 | function isAlmostConstantAssignment( |
| 144 | node: t.Node, |
| 145 | scope: Scope, |
| 146 | ): node is t.AssignmentExpression & { left: t.Identifier } { |
| 147 | if (!isAssignmentExpression(node) || !isIdentifier(node.left)) { |
| 148 | return false; |
| 149 | } |
| 150 | |
| 151 | // Not every scope can contain variables. For example, we might be in |
| 152 | // a ClassScope either in the ClassHeritage or in a computed key. |
| 153 | const blockScope = scope.getBlockParent(); |
| 154 | |
| 155 | // If the variable is defined in the current scope and only assigned here, |
| 156 | // we can be sure that its value won't change. |
| 157 | return ( |
| 158 | blockScope.hasOwnBinding(node.left.name) && |
| 159 | blockScope.getOwnBinding(node.left.name).constantViolations.length <= 1 |
| 160 | ); |
| 161 | } |
| 162 | |
| 163 | /** |
| 164 | * Insert the provided nodes after the current one. When inserting nodes after an |
| 165 | * expression, ensure that the completion record is correct by pushing the current node. |
| 166 | */ |
| 167 | |
| 168 | export function insertAfter( |
| 169 | this: NodePath, |
| 170 | nodes_: t.Node | t.Node[], |
| 171 | ): NodePath[] { |
| 172 | this._assertUnremoved(); |
| 173 | |
| 174 | if (this.isSequenceExpression()) { |
| 175 | return last(this.get("expressions")).insertAfter(nodes_); |
| 176 | } |
| 177 | |
| 178 | const nodes = this._verifyNodeList(nodes_); |
| 179 | |
| 180 | const { parentPath, parent } = this; |
| 181 | if ( |
| 182 | parentPath.isExpressionStatement() || |
| 183 | parentPath.isLabeledStatement() || |
| 184 | // see insertBefore |
| 185 | isExportNamedDeclaration(parent) || |
| 186 | (parentPath.isExportDefaultDeclaration() && this.isDeclaration()) |
| 187 | ) { |
| 188 | return parentPath.insertAfter( |
| 189 | nodes.map(node => { |
| 190 | // Usually after an expression we can safely insert another expression: |
| 191 | // A.insertAfter(B) |
| 192 | // foo = A; -> foo = (A, B); |
| 193 | // If A is an expression statement, it isn't safe anymore so we need to |
| 194 | // convert B to an expression statement |
| 195 | // A; -> A; B // No semicolon! It could break if followed by [! |
| 196 | return isExpression(node) ? expressionStatement(node) : node; |
| 197 | }), |
| 198 | ); |
| 199 | } else if ( |
| 200 | (this.isNodeType("Expression") && |
| 201 | !this.isJSXElement() && |
| 202 | !parentPath.isJSXElement()) || |
| 203 | (parentPath.isForStatement() && this.key === "init") |
| 204 | ) { |
| 205 | if (this.node) { |
| 206 | const node = this.node as t.Expression | t.VariableDeclaration; |
| 207 | let { scope } = this; |
| 208 | |
| 209 | if (scope.path.isPattern()) { |
| 210 | assertExpression(node); |
| 211 | |
| 212 | this.replaceWith(callExpression(arrowFunctionExpression([], node), [])); |
| 213 | (this.get("callee.body") as NodePath<t.Expression>).insertAfter(nodes); |
| 214 | return [this]; |
| 215 | } |
| 216 | |
| 217 | if (isHiddenInSequenceExpression(this)) { |
| 218 | nodes.unshift(node); |
| 219 | } |
| 220 | // We need to preserve the value of this expression. |
| 221 | else if (isCallExpression(node) && isSuper(node.callee)) { |
| 222 | nodes.unshift(node); |
| 223 | // `super(...)` always evaluates to `this`. |
| 224 | nodes.push(thisExpression()); |
| 225 | } else if (isAlmostConstantAssignment(node, scope)) { |
| 226 | nodes.unshift(node); |
| 227 | nodes.push(cloneNode(node.left)); |
| 228 | } else if (scope.isPure(node, true)) { |
| 229 | // Insert the nodes before rather than after; it's not observable. |
| 230 | nodes.push(node); |
| 231 | } else { |
| 232 | // Inserting after the computed key of a method should insert the |
| 233 | // temporary binding in the method's parent's scope. |
| 234 | if (parentPath.isMethod({ computed: true, key: node })) { |
| 235 | scope = scope.parent; |
| 236 | } |
| 237 | const temp = scope.generateDeclaredUidIdentifier(); |
| 238 | nodes.unshift( |
| 239 | expressionStatement( |
| 240 | // @ts-expect-error todo(flow->ts): This can be a variable |
| 241 | // declaraion in the "init" of a for statement, but that's |
| 242 | // invalid here. |
| 243 | assignmentExpression("=", cloneNode(temp), node), |
| 244 | ), |
| 245 | ); |
| 246 | nodes.push(expressionStatement(cloneNode(temp))); |
| 247 | } |
| 248 | } |
| 249 | // @ts-expect-error todo(flow->ts): check that nodes is an array of statements |
| 250 | return this.replaceExpressionWithStatements(nodes); |
| 251 | } else if (Array.isArray(this.container)) { |
| 252 | return this._containerInsertAfter(nodes); |
| 253 | } else if (this.isStatementOrBlock()) { |
| 254 | const node = this.node as t.Statement; |
| 255 | const shouldInsertCurrentNode = |
| 256 | node && |
| 257 | (!this.isExpressionStatement() || |
| 258 | (node as t.ExpressionStatement).expression != null); |
| 259 | |
| 260 | this.replaceWith(blockStatement(shouldInsertCurrentNode ? [node] : [])); |
| 261 | // @ts-expect-error Fixme: refine nodes to t.BlockStatement["body"] when this is a BlockStatement path |
| 262 | return this.pushContainer("body", nodes); |
| 263 | } else { |
| 264 | throw new Error( |
| 265 | "We don't know what to do with this node type. " + |
| 266 | "We were previously a Statement but we can't fit in here?", |
| 267 | ); |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | /** |
| 272 | * Update all sibling node paths after `fromIndex` by `incrementBy`. |
| 273 | */ |
| 274 | |
| 275 | export function updateSiblingKeys( |
| 276 | this: NodePath, |
| 277 | fromIndex: number, |
| 278 | incrementBy: number, |
| 279 | ) { |
| 280 | if (!this.parent) return; |
| 281 | |
| 282 | const paths = pathCache.get(this.parent); |
| 283 | for (const [, path] of paths) { |
| 284 | if (path.key >= fromIndex) { |
| 285 | path.key += incrementBy; |
| 286 | } |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | export function _verifyNodeList<N extends t.Node>( |
| 291 | this: NodePath, |
| 292 | nodes: N | N[], |
| 293 | ): N[] { |
| 294 | if (!nodes) { |
| 295 | return []; |
| 296 | } |
| 297 | |
| 298 | if (!Array.isArray(nodes)) { |
| 299 | nodes = [nodes]; |
| 300 | } |
| 301 | |
| 302 | for (let i = 0; i < nodes.length; i++) { |
| 303 | const node = nodes[i]; |
| 304 | let msg; |
| 305 | |
| 306 | if (!node) { |
| 307 | msg = "has falsy node"; |
| 308 | } else if (typeof node !== "object") { |
| 309 | msg = "contains a non-object node"; |
| 310 | } else if (!node.type) { |
| 311 | msg = "without a type"; |
| 312 | } else if (node instanceof NodePath) { |
| 313 | msg = "has a NodePath when it expected a raw object"; |
| 314 | } |
| 315 | |
| 316 | if (msg) { |
| 317 | const type = Array.isArray(node) ? "array" : typeof node; |
| 318 | throw new Error( |
| 319 | `Node list ${msg} with the index of ${i} and type of ${type}`, |
| 320 | ); |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | return nodes; |
| 325 | } |
| 326 | |
| 327 | export function unshiftContainer<N extends t.Node, K extends keyof N & string>( |
| 328 | this: NodePath<N>, |
| 329 | listKey: K, |
| 330 | nodes: N[K] extends (infer E)[] |
| 331 | ? E | E[] |
| 332 | : // todo: refine to t.Node[] |
| 333 | // ? E extends t.Node |
| 334 | // ? E | E[] |
| 335 | // : never |
| 336 | never, |
| 337 | ) { |
| 338 | // todo: NodePaths<Nodes> |
| 339 | this._assertUnremoved(); |
| 340 | |
| 341 | // @ts-expect-error fixme |
| 342 | nodes = this._verifyNodeList(nodes); |
| 343 | |
| 344 | // get the first path and insert our nodes before it, if it doesn't exist then it |
| 345 | // doesn't matter, our nodes will be inserted anyway |
| 346 | const path = NodePath.get({ |
| 347 | parentPath: this, |
| 348 | parent: this.node, |
| 349 | container: this.node[listKey] as unknown as t.Node | t.Node[], |
| 350 | listKey, |
| 351 | key: 0, |
| 352 | }).setContext(this.context); |
| 353 | |
| 354 | return path._containerInsertBefore( |
| 355 | // @ts-expect-error typings needed to narrow down nodes as t.Node[] |
| 356 | nodes, |
| 357 | ); |
| 358 | } |
| 359 | |
| 360 | export function pushContainer<N extends t.Node, K extends keyof N & string>( |
| 361 | this: NodePath<N>, |
| 362 | listKey: K, |
| 363 | nodes: N[K] extends (infer E)[] |
| 364 | ? E | E[] |
| 365 | : // todo: refine to t.Node[] |
| 366 | // ? E extends t.Node |
| 367 | // ? E | E[] |
| 368 | // : never |
| 369 | never, |
| 370 | ) { |
| 371 | this._assertUnremoved(); |
| 372 | |
| 373 | const verifiedNodes = this._verifyNodeList( |
| 374 | // @ts-expect-error refine typings |
| 375 | nodes, |
| 376 | ); |
| 377 | |
| 378 | // get an invisible path that represents the last node + 1 and replace it with our |
| 379 | // nodes, effectively inlining it |
| 380 | |
| 381 | const container = this.node[listKey]; |
| 382 | const path = NodePath.get({ |
| 383 | parentPath: this, |
| 384 | parent: this.node, |
| 385 | container: container as unknown as t.Node | t.Node[], |
| 386 | listKey, |
| 387 | // @ts-expect-error TS cannot infer that container is t.Node[] |
| 388 | key: container.length, |
| 389 | }).setContext(this.context); |
| 390 | |
| 391 | return path.replaceWithMultiple(verifiedNodes); |
| 392 | } |
| 393 | |
| 394 | /** |
| 395 | * Hoist the current node to the highest scope possible and return a UID |
| 396 | * referencing it. |
| 397 | */ |
| 398 | export function hoist<T extends t.Node>( |
| 399 | this: NodePath<T>, |
| 400 | scope: Scope = this.scope, |
| 401 | ) { |
| 402 | const hoister = new PathHoister<T>(this, scope); |
| 403 | return hoister.run(); |
| 404 | } |