hoisted

tcmts.cli.npm.hoisted · #jynf7dpe · term · runs anywhere

vars and function declarations in a function's body, not in functions inside it: hoisted to its scope.

import { bound, isFunctionLike } from "#codebase/tcmts/cli/npm";
import { forEachChild } from "#codebase/tcmts/core/ts";
import {
  isClassDeclaration, isClassExpression, isFunctionDeclaration, isVariableDeclarationList, NodeFlags,
} from "typescript/ast";
import type { Node } from "typescript/ast";

export function hoisted(body: Node | undefined, into: Set<string>) {
  if (!body) return;
  const visit = (n: Node) => {
    if (isFunctionDeclaration(n) && n.name) into.add(n.name.text);
    if (isFunctionLike(n) || isClassDeclaration(n) || isClassExpression(n)) return;
    if (isVariableDeclarationList(n) && !(n.flags & (NodeFlags.Let | NodeFlags.Const)))
      for (const d of n.declarations) for (const b of bound(d.name)) into.add(b);
    forEachChild(n, visit);
  };
  forEachChild(body, visit);
}

uses

used by