testDefPartsFindTheSyntaxWhereverItStarts

tcmts.core.ir.testDefPartsFindTheSyntaxWhereverItStarts · #hnokirqj · term

A definition's syntax is found after its head, salted or not, with a JSX runtime or not, parsed or serialized.

import { saltOf } from "#codebase/tcmts/core/analyze";
import type { IR } from "#codebase/tcmts/core/hash";
import { childOf, declarationOf, defParts, initializerOf } from "#codebase/tcmts/core/ir";
import { analyze } from "#codebase/tcmts/core/test/hash";
import assert from "node:assert/strict";

export const testDefPartsFindTheSyntaxWhereverItStarts = () => {
  const init: IR[] = ["Num", "3"];
  const decl: IR[] = ["VariableDeclaration", ["name", ["Named", "n"]], ["initializer", init]];
  const shapes: Record<string, IR[]> = {
    analyzed: ["Def", "Const", decl],
    salted: ["Def", "Const", ["Salt", "lib.n"], decl],
    jsx: ["Def", "Const", ["Jsx", "npm:react@19"], decl],
    both: ["Def", "Const", ["Salt", "lib.n"], ["Jsx", "npm:react@19"], decl],
  };
  for (const [what, ir] of Object.entries(shapes))
    for (const form of [ir, JSON.stringify(ir)]) {
      const parts = defParts(form);
      assert.equal(parts.tag, "Const", what);
      assert.deepEqual(parts.body, [decl], what);
      assert.deepEqual([...parts.head, ...parts.body], ir, `${what}: head and body are all of it`);
      assert.deepEqual(declarationOf(form), decl, what);
      assert.deepEqual(initializerOf(form), init, what);
    }
  assert.deepEqual(defParts(shapes.both!), {
    tag: "Const",
    salt: "lib.n",
    jsx: "npm:react@19",
    head: ["Def", "Const", ["Salt", "lib.n"], ["Jsx", "npm:react@19"]],
    body: [decl],
  });
  assert.equal(saltOf(JSON.stringify(shapes.salted)), "lib.n");
  assert.equal(saltOf(JSON.stringify(shapes.jsx)), undefined);
  assert.equal(childOf(decl, "name")?.[0], "Named");
  assert.equal(childOf(decl, "type"), undefined);
  // a file's IR isn't a definition's
  assert.deepEqual(defParts(["File", "text", "hello"]), { tag: "", head: [], body: [] });

  const [f, c, k] = analyze(
    `export function f(x: string): string;\nexport function f(x: unknown) { return x; }\n` +
      `export const c = () => 1;\nexport class K { m() {} }\n`,
  ).defs.map((d) => d.ir);
  assert.equal(
    defParts(f!).body.length,
    2,
    "an overloaded function: its signature, then its implementation",
  );
  assert.ok(childOf(declarationOf(f!), "body"), "its declaration is the implementation");
  assert.equal(initializerOf(c!)?.[0], "ArrowFunction");
  assert.equal(declarationOf(k!)?.[0], "ClassDeclaration");
  assert.equal(initializerOf(k!), undefined);
}

uses