testPureConstantsAreKept

tcmts.cli.test.e2e.effects.testPureConstantsAreKept · #wdrg6yp7 · term

A pure constant that computes something is evaluated once and kept: its module holds the value, and a run doesn't compute it again. One whose code reaches outside (the clock), writes out, or reads state something else could change first isn't: it's computed as written.

import { okIn, tempDir } from "#codebase/tcmts/cli/test/e2e/harness";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";

export const testPureConstantsAreKept = () => {
  const dir = tempDir("kept");
  const ok = (...args: string[]) => okIn(dir, ...args);
  ok("init");
  fs.writeFileSync(
    path.join(dir, "scratch.ts"),
    [
      "// tcm: namespace lib",
      "const fib = (n: number): number => (n < 2 ? n : fib(n - 1) + fib(n - 2));",
      "export const table = Array.from({ length: 25 }, (_, i) => fib(i));",
      "export const stamp = String(Date.now()).length;",
      "export const loud = (console.log('computing loud'), fib(10));",
      "export const registry: string[] = [];",
      "export const count = registry.push('a');",
      "export const main = (): number => (console.log(table[24], stamp > 0, loud, count), 0);",
      "",
    ].join("\n"),
  );
  ok("add");
  assert.match(ok("run", "lib.main"), /computing loud\n46368 true 55 1/);
  const cache = path.join(dir, ".tcm", "cache");
  const modules = fs
    .readdirSync(cache)
    .filter((f) => /^[a-z2-7]{52}\.ts$/.test(f))
    .map((f) => fs.readFileSync(path.join(cache, f), "utf8"))
    .join("\n");
  assert.match(
    modules,
    /const table = __tcm_kept\(\(\) => \(Array\.from[^\n]*\), \[0,1,1,2,3,5,8,/,
  );
  for (const name of ["stamp", "loud", "count"])
    assert.match(
      modules,
      new RegExp(`const ${name}(: [^=]+)? = (?!__tcm_kept)`),
      `${name} is computed as written`,
    );
  // the next run, the same
  assert.match(ok("run", "lib.main"), /computing loud\n46368 true 55 1/);
}

uses