| 1 | import * as virtualTypes from "./path/lib/virtual-types"; |
| 2 | import { DEPRECATED_KEYS, FLIPPED_ALIAS_KEYS, TYPES } from "@babel/types"; |
| 3 | import type { NodePath, Visitor } from "./index"; |
| 4 | |
| 5 | type VIRTUAL_TYPES = keyof typeof virtualTypes; |
| 6 | function isVirtualType(type: string): type is VIRTUAL_TYPES { |
| 7 | return type in virtualTypes; |
| 8 | } |
| 9 | |
| 10 | /** |
| 11 | * explode() will take a visitor object with all of the various shorthands |
| 12 | * that we support, and validates & normalizes it into a common format, ready |
| 13 | * to be used in traversal |
| 14 | * |
| 15 | * The various shorthands are: |
| 16 | * * `Identifier() { ... }` -> `Identifier: { enter() { ... } }` |
| 17 | * * `"Identifier|NumericLiteral": { ... }` -> `Identifier: { ... }, NumericLiteral: { ... }` |
| 18 | * * Aliases in `@babel/types`: e.g. `Property: { ... }` -> `ObjectProperty: { ... }, ClassProperty: { ... }` |
| 19 | * |
| 20 | * Other normalizations are: |
| 21 | * * Visitors of virtual types are wrapped, so that they are only visited when |
| 22 | * their dynamic check passes |
| 23 | * * `enter` and `exit` functions are wrapped in arrays, to ease merging of |
| 24 | * visitors |
| 25 | */ |
| 26 | export function explode(visitor: Visitor) { |
| 27 | if (visitor._exploded) return visitor; |
| 28 | visitor._exploded = true; |
| 29 | |
| 30 | // normalise pipes |
| 31 | for (const nodeType of Object.keys(visitor) as (keyof Visitor)[]) { |
| 32 | if (shouldIgnoreKey(nodeType)) continue; |
| 33 | |
| 34 | const parts: Array<string> = nodeType.split("|"); |
| 35 | if (parts.length === 1) continue; |
| 36 | |
| 37 | const fns = visitor[nodeType]; |
| 38 | delete visitor[nodeType]; |
| 39 | |
| 40 | for (const part of parts) { |
| 41 | // @ts-expect-error part will be verified by `verify` later |
| 42 | visitor[part] = fns; |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | // verify data structure |
| 47 | verify(visitor); |
| 48 | |
| 49 | // make sure there's no __esModule type since this is because we're using loose mode |
| 50 | // and it sets __esModule to be enumerable on all modules :( |
| 51 | // @ts-expect-error ESModule interop |
| 52 | delete visitor.__esModule; |
| 53 | |
| 54 | // ensure visitors are objects |
| 55 | ensureEntranceObjects(visitor); |
| 56 | |
| 57 | // ensure enter/exit callbacks are arrays |
| 58 | ensureCallbackArrays(visitor); |
| 59 | |
| 60 | // add type wrappers |
| 61 | for (const nodeType of Object.keys(visitor)) { |
| 62 | if (shouldIgnoreKey(nodeType)) continue; |
| 63 | |
| 64 | if (!isVirtualType(nodeType)) continue; |
| 65 | |
| 66 | // wrap all the functions |
| 67 | const fns = visitor[nodeType]; |
| 68 | for (const type of Object.keys(fns)) { |
| 69 | // @ts-expect-error manipulating visitors |
| 70 | fns[type] = wrapCheck(nodeType, fns[type]); |
| 71 | } |
| 72 | |
| 73 | // clear it from the visitor |
| 74 | delete visitor[nodeType]; |
| 75 | |
| 76 | const types = virtualTypes[nodeType]; |
| 77 | if (types !== null) { |
| 78 | for (const type of types) { |
| 79 | // merge the visitor if necessary or just put it back in |
| 80 | if (visitor[type]) { |
| 81 | mergePair(visitor[type], fns); |
| 82 | } else { |
| 83 | // @ts-expect-error Expression produces too complex union |
| 84 | visitor[type] = fns; |
| 85 | } |
| 86 | } |
| 87 | } else { |
| 88 | mergePair(visitor, fns); |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | // add aliases |
| 93 | for (const nodeType of Object.keys(visitor) as (keyof Visitor)[]) { |
| 94 | if (shouldIgnoreKey(nodeType)) continue; |
| 95 | |
| 96 | const fns = visitor[nodeType]; |
| 97 | |
| 98 | let aliases = FLIPPED_ALIAS_KEYS[nodeType]; |
| 99 | |
| 100 | const deprecatedKey = DEPRECATED_KEYS[nodeType]; |
| 101 | if (deprecatedKey) { |
| 102 | console.trace( |
| 103 | `Visitor defined for ${nodeType} but it has been renamed to ${deprecatedKey}`, |
| 104 | ); |
| 105 | aliases = [deprecatedKey]; |
| 106 | } |
| 107 | |
| 108 | if (!aliases) continue; |
| 109 | |
| 110 | // clear it from the visitor |
| 111 | delete visitor[nodeType]; |
| 112 | |
| 113 | for (const alias of aliases) { |
| 114 | const existing = visitor[alias]; |
| 115 | if (existing) { |
| 116 | mergePair(existing, fns); |
| 117 | } else { |
| 118 | // @ts-expect-error Expression produces a union type that is too complex to represent. |
| 119 | visitor[alias] = { ...fns }; |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | for (const nodeType of Object.keys(visitor)) { |
| 125 | if (shouldIgnoreKey(nodeType)) continue; |
| 126 | |
| 127 | ensureCallbackArrays( |
| 128 | // @ts-expect-error nodeType must present in visitor after previous validations |
| 129 | visitor[nodeType], |
| 130 | ); |
| 131 | } |
| 132 | |
| 133 | return visitor; |
| 134 | } |
| 135 | |
| 136 | export function verify(visitor: Visitor) { |
| 137 | if (visitor._verified) return; |
| 138 | |
| 139 | if (typeof visitor === "function") { |
| 140 | throw new Error( |
| 141 | "You passed `traverse()` a function when it expected a visitor object, " + |
| 142 | "are you sure you didn't mean `{ enter: Function }`?", |
| 143 | ); |
| 144 | } |
| 145 | |
| 146 | for (const nodeType of Object.keys(visitor) as (keyof Visitor)[]) { |
| 147 | if (nodeType === "enter" || nodeType === "exit") { |
| 148 | validateVisitorMethods(nodeType, visitor[nodeType]); |
| 149 | } |
| 150 | |
| 151 | if (shouldIgnoreKey(nodeType)) continue; |
| 152 | |
| 153 | if (TYPES.indexOf(nodeType) < 0) { |
| 154 | throw new Error( |
| 155 | `You gave us a visitor for the node type ${nodeType} but it's not a valid type`, |
| 156 | ); |
| 157 | } |
| 158 | |
| 159 | const visitors = visitor[nodeType]; |
| 160 | if (typeof visitors === "object") { |
| 161 | for (const visitorKey of Object.keys(visitors)) { |
| 162 | if (visitorKey === "enter" || visitorKey === "exit") { |
| 163 | // verify that it just contains functions |
| 164 | validateVisitorMethods( |
| 165 | `${nodeType}.${visitorKey}`, |
| 166 | visitors[visitorKey], |
| 167 | ); |
| 168 | } else { |
| 169 | throw new Error( |
| 170 | "You passed `traverse()` a visitor object with the property " + |
| 171 | `${nodeType} that has the invalid property ${visitorKey}`, |
| 172 | ); |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | visitor._verified = true; |
| 179 | } |
| 180 | |
| 181 | function validateVisitorMethods( |
| 182 | path: string, |
| 183 | val: any, |
| 184 | ): asserts val is Function | Function[] { |
| 185 | const fns = [].concat(val); |
| 186 | for (const fn of fns) { |
| 187 | if (typeof fn !== "function") { |
| 188 | throw new TypeError( |
| 189 | `Non-function found defined in ${path} with type ${typeof fn}`, |
| 190 | ); |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | export function merge<State>(visitors: Visitor<State>[]): Visitor<State>; |
| 196 | export function merge( |
| 197 | visitors: Visitor<unknown>[], |
| 198 | states?: any[], |
| 199 | wrapper?: Function | null, |
| 200 | ): Visitor<unknown>; |
| 201 | export function merge( |
| 202 | visitors: any[], |
| 203 | states: any[] = [], |
| 204 | wrapper?: Function | null, |
| 205 | ) { |
| 206 | const rootVisitor: Visitor = {}; |
| 207 | |
| 208 | for (let i = 0; i < visitors.length; i++) { |
| 209 | const visitor = visitors[i]; |
| 210 | const state = states[i]; |
| 211 | |
| 212 | explode(visitor); |
| 213 | |
| 214 | for (const type of Object.keys(visitor) as (keyof Visitor)[]) { |
| 215 | let visitorType = visitor[type]; |
| 216 | |
| 217 | // if we have state or wrapper then overload the callbacks to take it |
| 218 | if (state || wrapper) { |
| 219 | visitorType = wrapWithStateOrWrapper(visitorType, state, wrapper); |
| 220 | } |
| 221 | |
| 222 | // @ts-expect-error: Expression produces a union type that is too complex to represent. |
| 223 | const nodeVisitor = (rootVisitor[type] ||= {}); |
| 224 | mergePair(nodeVisitor, visitorType); |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | return rootVisitor; |
| 229 | } |
| 230 | |
| 231 | function wrapWithStateOrWrapper<State>( |
| 232 | oldVisitor: Visitor<State>, |
| 233 | state: State, |
| 234 | wrapper?: Function | null, |
| 235 | ) { |
| 236 | const newVisitor: Visitor = {}; |
| 237 | |
| 238 | for (const key of Object.keys(oldVisitor) as (keyof Visitor<State>)[]) { |
| 239 | let fns = oldVisitor[key]; |
| 240 | |
| 241 | // not an enter/exit array of callbacks |
| 242 | if (!Array.isArray(fns)) continue; |
| 243 | |
| 244 | // @ts-expect-error manipulating visitors |
| 245 | fns = fns.map(function (fn) { |
| 246 | let newFn = fn; |
| 247 | |
| 248 | if (state) { |
| 249 | newFn = function (path: NodePath) { |
| 250 | return fn.call(state, path, state); |
| 251 | }; |
| 252 | } |
| 253 | |
| 254 | if (wrapper) { |
| 255 | // @ts-expect-error Fixme: document state.key |
| 256 | newFn = wrapper(state.key, key, newFn); |
| 257 | } |
| 258 | |
| 259 | // Override toString in case this function is printed, we want to print the wrapped function, same as we do in `wrapCheck` |
| 260 | if (newFn !== fn) { |
| 261 | newFn.toString = () => fn.toString(); |
| 262 | } |
| 263 | |
| 264 | return newFn; |
| 265 | }); |
| 266 | |
| 267 | // @ts-expect-error: Expression produces a union type that is too complex to represent. |
| 268 | newVisitor[key] = fns; |
| 269 | } |
| 270 | |
| 271 | return newVisitor; |
| 272 | } |
| 273 | |
| 274 | function ensureEntranceObjects(obj: Visitor) { |
| 275 | for (const key of Object.keys(obj) as (keyof Visitor)[]) { |
| 276 | if (shouldIgnoreKey(key)) continue; |
| 277 | |
| 278 | const fns = obj[key]; |
| 279 | if (typeof fns === "function") { |
| 280 | // @ts-expect-error: Expression produces a union type that is too complex to represent. |
| 281 | obj[key] = { enter: fns }; |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | function ensureCallbackArrays(obj: Visitor) { |
| 287 | // @ts-expect-error normalizing enter property |
| 288 | if (obj.enter && !Array.isArray(obj.enter)) obj.enter = [obj.enter]; |
| 289 | // @ts-expect-error normalizing exit property |
| 290 | if (obj.exit && !Array.isArray(obj.exit)) obj.exit = [obj.exit]; |
| 291 | } |
| 292 | |
| 293 | function wrapCheck(nodeType: VIRTUAL_TYPES, fn: Function) { |
| 294 | const newFn = function (this: unknown, path: NodePath) { |
| 295 | if (path[`is${nodeType}`]()) { |
| 296 | return fn.apply(this, arguments); |
| 297 | } |
| 298 | }; |
| 299 | newFn.toString = () => fn.toString(); |
| 300 | return newFn; |
| 301 | } |
| 302 | |
| 303 | function shouldIgnoreKey( |
| 304 | key: string, |
| 305 | ): key is |
| 306 | | "enter" |
| 307 | | "exit" |
| 308 | | "shouldSkip" |
| 309 | | "denylist" |
| 310 | | "noScope" |
| 311 | | "skipKeys" |
| 312 | | "blacklist" { |
| 313 | // internal/hidden key |
| 314 | if (key[0] === "_") return true; |
| 315 | |
| 316 | // ignore function keys |
| 317 | if (key === "enter" || key === "exit" || key === "shouldSkip") return true; |
| 318 | |
| 319 | // ignore other options |
| 320 | if ( |
| 321 | key === "denylist" || |
| 322 | key === "noScope" || |
| 323 | key === "skipKeys" || |
| 324 | // TODO: Remove in Babel 8 |
| 325 | key === "blacklist" |
| 326 | ) { |
| 327 | return true; |
| 328 | } |
| 329 | |
| 330 | return false; |
| 331 | } |
| 332 | |
| 333 | function mergePair(dest: any, src: any) { |
| 334 | for (const key of Object.keys(src)) { |
| 335 | dest[key] = [].concat(dest[key] || [], src[key]); |
| 336 | } |
| 337 | } |