| 1 | import { react } from "@babel/types"; |
| 2 | import { |
| 3 | cloneNode, |
| 4 | jsxExpressionContainer, |
| 5 | variableDeclaration, |
| 6 | variableDeclarator, |
| 7 | } from "@babel/types"; |
| 8 | import type * as t from "@babel/types"; |
| 9 | import type Scope from "../../scope"; |
| 10 | import type NodePath from "../index"; |
| 11 | import type Binding from "../../scope/binding"; |
| 12 | import type { Visitor } from "../../types"; |
| 13 | |
| 14 | const referenceVisitor: Visitor<PathHoister> = { |
| 15 | // This visitor looks for bindings to establish a topmost scope for hoisting. |
| 16 | ReferencedIdentifier(path, state) { |
| 17 | // Don't hoist regular JSX identifiers ('div', 'span', etc). |
| 18 | // We do have to consider member expressions for hoisting (e.g. `this.component`) |
| 19 | if ( |
| 20 | path.isJSXIdentifier() && |
| 21 | react.isCompatTag(path.node.name) && |
| 22 | !path.parentPath.isJSXMemberExpression() |
| 23 | ) { |
| 24 | return; |
| 25 | } |
| 26 | |
| 27 | // If the identifier refers to `this`, we need to break on the closest non-arrow scope. |
| 28 | if (path.node.name === "this") { |
| 29 | let scope = path.scope; |
| 30 | do { |
| 31 | if ( |
| 32 | scope.path.isFunction() && |
| 33 | !scope.path.isArrowFunctionExpression() |
| 34 | ) { |
| 35 | break; |
| 36 | } |
| 37 | } while ((scope = scope.parent)); |
| 38 | if (scope) state.breakOnScopePaths.push(scope.path); |
| 39 | } |
| 40 | |
| 41 | // direct references that we need to track to hoist this to the highest scope we can |
| 42 | const binding = path.scope.getBinding(path.node.name); |
| 43 | if (!binding) return; |
| 44 | |
| 45 | // we can handle reassignments only if they happen in the same scope as the declaration |
| 46 | for (const violation of binding.constantViolations) { |
| 47 | if (violation.scope !== binding.path.scope) { |
| 48 | state.mutableBinding = true; |
| 49 | path.stop(); |
| 50 | return; |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | // this binding isn't accessible from the parent scope so we can safely ignore it |
| 55 | // eg. it's in a closure etc |
| 56 | if (binding !== state.scope.getBinding(path.node.name)) return; |
| 57 | |
| 58 | state.bindings[path.node.name] = binding; |
| 59 | }, |
| 60 | }; |
| 61 | |
| 62 | export default class PathHoister<T extends t.Node = t.Node> { |
| 63 | breakOnScopePaths: NodePath[]; |
| 64 | bindings: { [k: string]: Binding }; |
| 65 | mutableBinding: boolean; |
| 66 | private scopes: Scope[]; |
| 67 | scope: Scope; |
| 68 | private path: NodePath<T>; |
| 69 | private attachAfter: boolean; |
| 70 | |
| 71 | constructor(path: NodePath<T>, scope: Scope) { |
| 72 | // Storage for scopes we can't hoist above. |
| 73 | this.breakOnScopePaths = []; |
| 74 | // Storage for bindings that may affect what path we can hoist to. |
| 75 | this.bindings = {}; |
| 76 | // "true" if the current path contains a reference to a binding whose |
| 77 | // value can change and thus can't be safely hoisted. |
| 78 | this.mutableBinding = false; |
| 79 | // Storage for eligible scopes. |
| 80 | this.scopes = []; |
| 81 | // Our original scope and path. |
| 82 | this.scope = scope; |
| 83 | this.path = path; |
| 84 | // By default, we attach as far up as we can; but if we're trying |
| 85 | // to avoid referencing a binding, we may have to go after. |
| 86 | this.attachAfter = false; |
| 87 | } |
| 88 | |
| 89 | // A scope is compatible if all required bindings are reachable. |
| 90 | isCompatibleScope(scope: Scope) { |
| 91 | for (const key of Object.keys(this.bindings)) { |
| 92 | const binding = this.bindings[key]; |
| 93 | if (!scope.bindingIdentifierEquals(key, binding.identifier)) { |
| 94 | return false; |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | return true; |
| 99 | } |
| 100 | |
| 101 | // Look through all scopes and push compatible ones. |
| 102 | getCompatibleScopes() { |
| 103 | let scope = this.path.scope; |
| 104 | do { |
| 105 | if (this.isCompatibleScope(scope)) { |
| 106 | this.scopes.push(scope); |
| 107 | } else { |
| 108 | break; |
| 109 | } |
| 110 | |
| 111 | // deopt: These scopes are set in the visitor on const violations |
| 112 | if (this.breakOnScopePaths.indexOf(scope.path) >= 0) { |
| 113 | break; |
| 114 | } |
| 115 | } while ((scope = scope.parent)); |
| 116 | } |
| 117 | |
| 118 | getAttachmentPath() { |
| 119 | let path = this._getAttachmentPath(); |
| 120 | if (!path) return; |
| 121 | |
| 122 | let targetScope = path.scope; |
| 123 | |
| 124 | // don't allow paths that have their own lexical environments to pollute |
| 125 | if (targetScope.path === path) { |
| 126 | targetScope = path.scope.parent; |
| 127 | } |
| 128 | |
| 129 | // avoid hoisting to a scope that contains bindings that are executed after our attachment path |
| 130 | if (targetScope.path.isProgram() || targetScope.path.isFunction()) { |
| 131 | for (const name of Object.keys(this.bindings)) { |
| 132 | // check binding is a direct child of this paths scope |
| 133 | if (!targetScope.hasOwnBinding(name)) continue; |
| 134 | |
| 135 | const binding = this.bindings[name]; |
| 136 | |
| 137 | // allow parameter references and expressions in params (like destructuring rest) |
| 138 | if (binding.kind === "param" || binding.path.parentKey === "params") { |
| 139 | continue; |
| 140 | } |
| 141 | |
| 142 | // For each binding, get its attachment parent. This gives us an idea of where we might |
| 143 | // introduce conflicts. |
| 144 | const bindingParentPath = this.getAttachmentParentForPath(binding.path); |
| 145 | |
| 146 | // If the binding's attachment appears at or after our attachment point, then we move after it. |
| 147 | if (bindingParentPath.key >= path.key) { |
| 148 | this.attachAfter = true; |
| 149 | path = binding.path; |
| 150 | |
| 151 | // We also move past any constant violations. |
| 152 | for (const violationPath of binding.constantViolations) { |
| 153 | if (this.getAttachmentParentForPath(violationPath).key > path.key) { |
| 154 | path = violationPath; |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | return path; |
| 162 | } |
| 163 | |
| 164 | _getAttachmentPath() { |
| 165 | const scopes = this.scopes; |
| 166 | |
| 167 | const scope = scopes.pop(); |
| 168 | // deopt: no compatible scopes |
| 169 | if (!scope) return; |
| 170 | |
| 171 | if (scope.path.isFunction()) { |
| 172 | if (this.hasOwnParamBindings(scope)) { |
| 173 | // deopt: should ignore this scope since it's ourselves |
| 174 | if (this.scope === scope) return; |
| 175 | |
| 176 | // needs to be attached to the body |
| 177 | const bodies = scope.path.get("body").get("body") as NodePath[]; |
| 178 | for (let i = 0; i < bodies.length; i++) { |
| 179 | // Don't attach to something that's going to get hoisted, |
| 180 | // like a default parameter |
| 181 | // @ts-expect-error todo(flow->ts): avoid mutating the node, introducing new fields |
| 182 | if (bodies[i].node._blockHoist) continue; |
| 183 | return bodies[i]; |
| 184 | } |
| 185 | // deopt: If here, no attachment path found |
| 186 | } else { |
| 187 | // doesn't need to be be attached to this scope |
| 188 | return this.getNextScopeAttachmentParent(); |
| 189 | } |
| 190 | } else if (scope.path.isProgram()) { |
| 191 | return this.getNextScopeAttachmentParent(); |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | getNextScopeAttachmentParent() { |
| 196 | const scope = this.scopes.pop(); |
| 197 | if (scope) return this.getAttachmentParentForPath(scope.path); |
| 198 | } |
| 199 | |
| 200 | // Find an attachment for this path. |
| 201 | getAttachmentParentForPath(path: NodePath) { |
| 202 | do { |
| 203 | if ( |
| 204 | // Beginning of the scope |
| 205 | !path.parentPath || |
| 206 | // Has siblings and is a statement |
| 207 | (Array.isArray(path.container) && path.isStatement()) |
| 208 | ) { |
| 209 | return path; |
| 210 | } |
| 211 | } while ((path = path.parentPath)); |
| 212 | } |
| 213 | |
| 214 | // Returns true if a scope has param bindings. |
| 215 | hasOwnParamBindings(scope: Scope) { |
| 216 | for (const name of Object.keys(this.bindings)) { |
| 217 | if (!scope.hasOwnBinding(name)) continue; |
| 218 | |
| 219 | const binding = this.bindings[name]; |
| 220 | // Ensure constant; without it we could place behind a reassignment |
| 221 | if (binding.kind === "param" && binding.constant) return true; |
| 222 | } |
| 223 | return false; |
| 224 | } |
| 225 | |
| 226 | run() { |
| 227 | this.path.traverse(referenceVisitor, this); |
| 228 | |
| 229 | if (this.mutableBinding) return; |
| 230 | |
| 231 | this.getCompatibleScopes(); |
| 232 | |
| 233 | const attachTo = this.getAttachmentPath(); |
| 234 | if (!attachTo) return; |
| 235 | |
| 236 | // don't bother hoisting to the same function as this will cause multiple branches to be |
| 237 | // evaluated more than once leading to a bad optimisation |
| 238 | if (attachTo.getFunctionParent() === this.path.getFunctionParent()) return; |
| 239 | |
| 240 | // generate declaration and insert it to our point |
| 241 | let uid: t.Identifier | t.JSXExpressionContainer = |
| 242 | attachTo.scope.generateUidIdentifier("ref"); |
| 243 | |
| 244 | // @ts-expect-error todo(flow->ts): more specific type for this.path |
| 245 | const declarator = variableDeclarator(uid, this.path.node); |
| 246 | |
| 247 | const insertFn = this.attachAfter ? "insertAfter" : "insertBefore"; |
| 248 | const [attached] = attachTo[insertFn]([ |
| 249 | attachTo.isVariableDeclarator() |
| 250 | ? declarator |
| 251 | : variableDeclaration("var", [declarator]), |
| 252 | ]); |
| 253 | |
| 254 | const parent = this.path.parentPath; |
| 255 | if (parent.isJSXElement() && this.path.container === parent.node.children) { |
| 256 | // turning the `span` in `<div><span /></div>` to an expression so we need to wrap it with |
| 257 | // an expression container |
| 258 | uid = jsxExpressionContainer(uid); |
| 259 | } |
| 260 | |
| 261 | this.path.replaceWith(cloneNode(uid)); |
| 262 | |
| 263 | return attachTo.isVariableDeclarator() |
| 264 | ? attached.get("init") |
| 265 | : attached.get("declarations.0.init"); |
| 266 | } |
| 267 | } |