| 1 | import { |
| 2 | assignmentExpression, |
| 3 | expressionStatement, |
| 4 | identifier, |
| 5 | } from "@babel/types"; |
| 6 | import type * as t from "@babel/types"; |
| 7 | import type { NodePath, Visitor } from "@babel/traverse"; |
| 8 | |
| 9 | export type EmitFunction = ( |
| 10 | id: t.Identifier, |
| 11 | idName: string, |
| 12 | hasInit: boolean, |
| 13 | ) => any; |
| 14 | |
| 15 | type State = { |
| 16 | kind: "var" | "let"; |
| 17 | emit: EmitFunction; |
| 18 | }; |
| 19 | |
| 20 | type Unpacked<T> = T extends (infer U)[] ? U : T; |
| 21 | |
| 22 | const visitor: Visitor<State> = { |
| 23 | Scope(path, state) { |
| 24 | if (state.kind === "let") path.skip(); |
| 25 | }, |
| 26 | |
| 27 | FunctionParent(path) { |
| 28 | path.skip(); |
| 29 | }, |
| 30 | |
| 31 | VariableDeclaration(path, state) { |
| 32 | if (state.kind && path.node.kind !== state.kind) return; |
| 33 | |
| 34 | const nodes = []; |
| 35 | |
| 36 | const declarations: ReadonlyArray< |
| 37 | NodePath<Unpacked<t.VariableDeclaration["declarations"]>> |
| 38 | > = path.get("declarations"); |
| 39 | let firstId; |
| 40 | |
| 41 | for (const declar of declarations) { |
| 42 | firstId = declar.node.id; |
| 43 | |
| 44 | if (declar.node.init) { |
| 45 | nodes.push( |
| 46 | expressionStatement( |
| 47 | assignmentExpression("=", declar.node.id, declar.node.init), |
| 48 | ), |
| 49 | ); |
| 50 | } |
| 51 | |
| 52 | for (const name of Object.keys(declar.getBindingIdentifiers())) { |
| 53 | state.emit(identifier(name), name, declar.node.init !== null); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | // for (var i in test) |
| 58 | if (path.parentPath.isFor({ left: path.node })) { |
| 59 | path.replaceWith(firstId); |
| 60 | } else { |
| 61 | path.replaceWithMultiple(nodes); |
| 62 | } |
| 63 | }, |
| 64 | }; |
| 65 | |
| 66 | export default function hoistVariables( |
| 67 | path: NodePath, |
| 68 | emit: EmitFunction, |
| 69 | kind: "var" | "let" = "var", |
| 70 | ) { |
| 71 | path.traverse(visitor, { kind, emit }); |
| 72 | } |