@skillstech/thunderlang 1.0.4 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +140 -0
  2. package/dist/core.cjs +2568 -462
  3. package/dist/index.cjs +7562 -5084
  4. package/dist/learn.cjs +1963 -315
  5. package/intent-graph.schema.json +11 -0
  6. package/package.json +6 -2
  7. package/src/cli.mjs +141 -58
  8. package/src/codegen.mjs +145 -55
  9. package/src/conformance.mjs +15 -6
  10. package/src/core/check.mjs +725 -0
  11. package/src/core/cli.mjs +133 -0
  12. package/src/core/diagnostics.mjs +81 -0
  13. package/src/core/format.mjs +20 -0
  14. package/src/core/from-python.mjs +645 -0
  15. package/src/core/index.mjs +38 -0
  16. package/src/core/lexer.mjs +115 -0
  17. package/src/core/parser.mjs +742 -0
  18. package/src/core/project.mjs +167 -0
  19. package/src/core/round-trip.mjs +150 -0
  20. package/src/core/runtime-python.mjs +801 -0
  21. package/src/core/target-python.mjs +486 -0
  22. package/src/core.d.ts +5 -2
  23. package/src/core.mjs +5 -2
  24. package/src/data-schema.mjs +8 -1
  25. package/src/emit.mjs +1 -1
  26. package/src/evidence.mjs +1 -1
  27. package/src/expr.mjs +81 -4
  28. package/src/form-words.mjs +2 -0
  29. package/src/index.d.ts +8 -1
  30. package/src/index.mjs +5 -1
  31. package/src/intent-schema.mjs +1 -0
  32. package/src/mcp.mjs +23 -0
  33. package/src/meaning.mjs +45 -6
  34. package/src/model.d.mts +7 -3
  35. package/src/model.mjs +19 -6
  36. package/src/money.d.mts +18 -0
  37. package/src/money.mjs +124 -0
  38. package/src/plain-contract.mjs +18 -2
  39. package/src/read.d.mts +11 -0
  40. package/src/read.mjs +40 -6
  41. package/src/review-comment.d.mts +16 -0
  42. package/src/review-comment.mjs +145 -0
  43. package/src/say-less.mjs +1432 -0
  44. package/src/system.mjs +153 -44
  45. package/src/target-cs.mjs +39 -34
  46. package/src/target-elixir.mjs +40 -30
  47. package/src/target-go.mjs +41 -36
  48. package/src/target-java.mjs +34 -27
  49. package/src/target-kotlin.mjs +43 -35
  50. package/src/target-py.mjs +57 -55
  51. package/src/target-result.d.mts +48 -0
  52. package/src/target-result.mjs +112 -0
  53. package/src/target-rust.mjs +42 -38
  54. package/src/target-scala.mjs +45 -35
  55. package/src/target-ts.mjs +37 -45
  56. package/src/target-types.mjs +41 -5
  57. package/src/target-util.mjs +55 -2
  58. package/src/trace-cli.mjs +58 -0
  59. package/src/trace-fs.mjs +76 -0
  60. package/src/trace.mjs +261 -0
  61. package/src/translate.d.mts +3 -0
  62. package/src/translate.mjs +62 -32
  63. package/src/why-cli.mjs +31 -0
  64. package/src/why.d.mts +28 -0
  65. package/src/why.mjs +532 -0
  66. package/src/write-steps.mjs +22 -5
@@ -0,0 +1,167 @@
1
+ // Thunder Core projects on disk: thunder.toml, src/, tests/, generated/python/.
2
+ //
3
+ // Source ownership: in a Thunder project the .thunder files are the source. generated/ is a build artifact,
4
+ // rewritten by every build; it is never read back.
5
+
6
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync, rmSync } from 'node:fs';
7
+ import { join, dirname, relative, resolve, basename } from 'node:path';
8
+ import { spawnSync } from 'node:child_process';
9
+ import { compileCore } from './index.mjs';
10
+ import { PYTHON_RUNTIME } from './runtime-python.mjs';
11
+
12
+ export const PROJECT_FILE = 'thunder.toml';
13
+
14
+ /** A tiny TOML subset: [sections], key = "text" | number | true | false, and # comments. */
15
+ export function parseToml(text) {
16
+ const out = {};
17
+ let section = out;
18
+ text.split(/\r?\n/).forEach((raw, i) => {
19
+ const line = raw.replace(/(^|\s)#.*$/, '').trim();
20
+ if (!line) return;
21
+ const sec = line.match(/^\[([A-Za-z0-9_.-]+)\]$/);
22
+ if (sec) { section = out[sec[1]] ??= {}; return; }
23
+ const kv = line.match(/^([A-Za-z0-9_-]+)\s*=\s*(.+)$/);
24
+ if (!kv) throw new Error(`thunder.toml, line ${i + 1}: I can't read "${raw.trim()}". Write key = "value".`);
25
+ const v = kv[2].trim();
26
+ section[kv[1]] = /^".*"$/.test(v) ? JSON.parse(v) : v === 'true' ? true : v === 'false' ? false : /^-?\d+(\.\d+)?$/.test(v) ? Number(v) : v;
27
+ });
28
+ return out;
29
+ }
30
+
31
+ /** The nearest folder at or above `start` that holds a thunder.toml, or null. */
32
+ export function findProjectRoot(start) {
33
+ let dir = resolve(start);
34
+ if (existsSync(dir) && !statSync(dir).isDirectory()) dir = dirname(dir);
35
+ for (;;) {
36
+ if (existsSync(join(dir, PROJECT_FILE))) return dir;
37
+ const up = dirname(dir);
38
+ if (up === dir) return null;
39
+ dir = up;
40
+ }
41
+ }
42
+
43
+ export function loadProject(root) {
44
+ const toml = parseToml(readFileSync(join(root, PROJECT_FILE), 'utf8'));
45
+ const build = toml.build ?? {};
46
+ const target = String(build.target ?? 'python');
47
+ if (target !== 'python') throw new Error(`thunder.toml: target "${target}" is not supported yet. Thunder Core v0 builds Python (target = "python").`);
48
+ return {
49
+ root,
50
+ name: toml.project?.name ?? basename(root),
51
+ version: toml.project?.version ?? '0.1.0',
52
+ target,
53
+ src: build.source ?? 'src',
54
+ tests: build.tests ?? 'tests',
55
+ out: build.output ?? 'generated/python',
56
+ entry: build.entry ?? null,
57
+ };
58
+ }
59
+
60
+ const thunderFiles = (dir) => (existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith('.thunder')).sort().map((f) => join(dir, f)) : []);
61
+
62
+ // Python standard-library modules a generated file must not shadow (a src/csv.thunder must not become csv.py).
63
+ const STDLIB = new Set('abc argparse array ast asyncio base64 bisect calendar cmath code collections contextlib copy csv dataclasses datetime decimal difflib dis email enum fractions functools getpass glob gzip hashlib heapq hmac html http importlib inspect io ipaddress itertools json keyword linecache locale logging math mimetypes numbers operator os pathlib pickle platform pprint queue random re secrets select shutil signal site socket sqlite3 statistics string struct subprocess sys tempfile test tests textwrap this threading time timeit token tokenize traceback types typing unicodedata unittest urllib uuid warnings weakref xml zipfile zlib thunder_runtime run_tests'.split(' '));
64
+
65
+ export function moduleNameFor(file) {
66
+ let n = basename(file, '.thunder').toLowerCase().replace(/[^a-z0-9_]+/g, '_').replace(/^(\d)/, '_$1') || 'program';
67
+ if (STDLIB.has(n)) n = `${n}_program`;
68
+ return n;
69
+ }
70
+
71
+ /**
72
+ * Compile a project (or a single file when `single` is given). Writes generated/python/<module>.py for every
73
+ * file plus thunder_runtime.py. Returns { ok, results: [{ file, module, ok, diagnostics }], outDir, entryModule }.
74
+ */
75
+ export function buildProject({ root, single = null, includeTests = false, write = true, config = null }) {
76
+ const cfg = config ?? (single && !findProjectRoot(single) ? null : loadProject(root));
77
+ const base = cfg ? cfg.root : dirname(resolve(single));
78
+ const srcFiles = cfg ? thunderFiles(join(cfg.root, cfg.src)) : [];
79
+ if (single && !srcFiles.includes(resolve(single))) srcFiles.unshift(resolve(single));
80
+ const testFiles = includeTests && cfg ? thunderFiles(join(cfg.root, cfg.tests)) : [];
81
+ const outDir = join(base, cfg ? cfg.out : 'generated/python');
82
+ const results = [];
83
+ const used = new Set();
84
+ const uniqueModule = (f, prefix = '') => { let n = prefix + moduleNameFor(f); let k = 2; while (used.has(n)) n = `${prefix}${moduleNameFor(f)}_${k++}`; used.add(n); return n; };
85
+ for (const f of srcFiles) {
86
+ const rel = relative(base, f).split('\\').join('/');
87
+ const r = compileCore(readFileSync(f, 'utf8'), { file: rel });
88
+ results.push({ ...r, path: f, rel, module: uniqueModule(f), kind: 'src' });
89
+ }
90
+ const srcOk = results.filter((r) => r.ok);
91
+ for (const f of testFiles) {
92
+ const rel = relative(base, f).split('\\').join('/');
93
+ const r = compileCore(readFileSync(f, 'utf8'), { file: rel, imported: srcOk, srcModules: srcOk.map((x) => x.module) });
94
+ results.push({ ...r, path: f, rel, module: uniqueModule(f, 'tests_'), kind: 'test' });
95
+ }
96
+ const ok = results.every((r) => r.ok);
97
+ if (ok && write) {
98
+ mkdirSync(outDir, { recursive: true });
99
+ writeFileSync(join(outDir, 'thunder_runtime.py'), PYTHON_RUNTIME);
100
+ for (const r of results) writeFileSync(join(outDir, `${r.module}.py`), r.python);
101
+ writeFileSync(join(outDir, 'run_tests.py'), [
102
+ '# Generated by the Thunder compiler: runs every Test block in this project. Run with: python3 run_tests.py',
103
+ 'import thunder_runtime',
104
+ ...results.map((r) => `import ${r.module}`),
105
+ '',
106
+ `thunder_runtime.run_tests([${results.map((r) => r.module).join(', ')}])`,
107
+ '',
108
+ ].join('\n'));
109
+ }
110
+ const entryPath = single ? resolve(single) : cfg?.entry ? join(cfg.root, cfg.entry) : join(base, cfg?.src ?? '.', 'main.thunder');
111
+ const entry = results.find((r) => r.path === entryPath) ?? results.find((r) => r.kind === 'src');
112
+ return { ok, results, outDir, base, entryModule: entry?.module ?? null, entry, config: cfg };
113
+ }
114
+
115
+ /** The local Python 3.10+: $THUNDER_PYTHON, then python3, then python. Returns { cmd, version } or { error }. */
116
+ export function findPython() {
117
+ const candidates = [process.env.THUNDER_PYTHON, 'python3', 'python'].filter(Boolean);
118
+ for (const cmd of candidates) {
119
+ const r = spawnSync(cmd, ['-c', 'import sys; print("%d.%d" % sys.version_info[:2])'], { encoding: 'utf8' });
120
+ if (r.status !== 0 || !r.stdout) continue;
121
+ const [maj, min] = r.stdout.trim().split('.').map(Number);
122
+ if (maj > 3 || (maj === 3 && min >= 10)) return { cmd, version: r.stdout.trim() };
123
+ return { error: `Thunder needs Python 3.10 or newer, but "${cmd}" is Python ${r.stdout.trim()}. Install a newer Python from https://www.python.org/downloads/ or set THUNDER_PYTHON to its path.` };
124
+ }
125
+ return { error: 'Thunder needs Python 3.10 or newer to run this program, and I could not find it (tried THUNDER_PYTHON, python3, python). Install it from https://www.python.org/downloads/ or set THUNDER_PYTHON to its path. "thunder build" still works without Python.' };
126
+ }
127
+
128
+ export function runPython(python, outDir, script, cwd) {
129
+ return spawnSync(python.cmd, [join(outDir, script)], { cwd, stdio: 'inherit', env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1', PYTHONIOENCODING: 'utf-8', PYTHONUNBUFFERED: '1' } });
130
+ }
131
+
132
+ export function newProject(dir, { force = false } = {}) {
133
+ const root = resolve(dir);
134
+ if (existsSync(join(root, PROJECT_FILE)) && !force) throw new Error(`${join(dir, PROJECT_FILE)} already exists (use --force to overwrite).`);
135
+ const name = basename(root);
136
+ mkdirSync(join(root, 'src'), { recursive: true });
137
+ mkdirSync(join(root, 'tests'), { recursive: true });
138
+ writeFileSync(join(root, PROJECT_FILE), `# A Thunder project. The .thunder files in src/ are the source; generated/ is rebuilt from them.
139
+ [project]
140
+ name = "${name}"
141
+ version = "0.1.0"
142
+
143
+ [build]
144
+ target = "python"
145
+ source = "src"
146
+ tests = "tests"
147
+ output = "generated/python"
148
+ entry = "src/main.thunder"
149
+ `);
150
+ writeFileSync(join(root, 'src', 'main.thunder'), `# Your first Thunder program. Run it with: thunder run
151
+
152
+ To greet:
153
+ Receive name
154
+ Give "Hello, {name}!"
155
+
156
+ say greet with "world"
157
+ `);
158
+ writeFileSync(join(root, 'tests', 'greet.thunder'), `# Tests see everything in src/. Run them with: thunder test
159
+
160
+ Test "greet says hello":
161
+ Expect greet with "Ada" to be "Hello, Ada!"
162
+ `);
163
+ writeFileSync(join(root, '.gitignore'), 'generated/\n');
164
+ return root;
165
+ }
166
+
167
+ export function cleanOutput(outDir) { if (existsSync(outDir)) rmSync(outDir, { recursive: true, force: true }); }
@@ -0,0 +1,150 @@
1
+ // Round trip, checked by running: Python → Thunder Core → Python again, compared on real inputs. Node only.
2
+ //
3
+ // For each input, the ORIGINAL Python function and the function compiled from its Thunder Core are both called, and
4
+ // three things are compared: the value given back, what was printed, and whether (and with what message) it stopped
5
+ // with an error. "Same" is claimed only when all three match. Numbers match when they are equal as decimals, or
6
+ // within 1e-9 of each other when the original used binary floats (0.30000000000000004 vs Core's exact 0.3); that
7
+ // tolerance is reported, never hidden.
8
+
9
+ import { spawnSync } from 'node:child_process';
10
+ import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ import { tmpdir } from 'node:os';
13
+ import { compileCore, PYTHON_RUNTIME } from './index.mjs';
14
+ import { findPython } from './project.mjs';
15
+
16
+ const HARNESS = String.raw`
17
+ import io, json, sys, contextlib, importlib, math
18
+ from decimal import Decimal
19
+ from types import SimpleNamespace as O
20
+
21
+ plan = json.load(open(sys.argv[1]))
22
+ orig = importlib.import_module("original")
23
+ core = importlib.import_module("from_core")
24
+
25
+ def norm(v):
26
+ if isinstance(v, bool) or v is None or isinstance(v, str):
27
+ return v
28
+ if isinstance(v, (int, float, Decimal)):
29
+ return {"number": str(v), "float": isinstance(v, float)}
30
+ if type(v).__name__ == "Money":
31
+ return {"number": str(v.amount), "float": False}
32
+ if isinstance(v, (list, tuple)):
33
+ return [norm(x) for x in v]
34
+ if isinstance(v, dict):
35
+ return {"map": [[norm(k), norm(x)] for k, x in v.items()]}
36
+ if isinstance(v, O) or hasattr(v, "__dict__"):
37
+ return {"record": {k: norm(x) for k, x in sorted(vars(v).items())}}
38
+ return {"other": repr(v)}
39
+
40
+ def call(fn, args):
41
+ out = io.StringIO()
42
+ try:
43
+ with contextlib.redirect_stdout(out):
44
+ value = fn(*args)
45
+ return {"value": norm(value), "printed": out.getvalue(), "error": None}
46
+ except Exception as e:
47
+ return {"value": None, "printed": out.getvalue(), "error": str(e), "kinds": [c.__name__ for c in type(e).__mro__]}
48
+
49
+ def python_fn(args):
50
+ kind = plan.get("kind", "function")
51
+ if kind == "method": # obj.method(rest): the object is the first input
52
+ return lambda *a: getattr(a[0], plan["python"])(*a[1:])
53
+ if kind == "static":
54
+ return getattr(getattr(orig, plan["cls"]), plan["python"])
55
+ return getattr(orig, plan["python"])
56
+
57
+ env = {"O": O, **{k: v for k, v in vars(orig).items() if not k.startswith("__")}}
58
+ results = []
59
+ for case in plan["inputs"]:
60
+ args = eval("(" + case + ",)", env)
61
+ a = call(python_fn(args), args)
62
+ if plan.get("kind") == "method":
63
+ a["after"] = norm(args[0])
64
+ args = eval("(" + case + ",)", env)
65
+ b = call(getattr(core, plan["core"]), args)
66
+ if plan.get("kind") == "method":
67
+ b["after"] = norm(args[0])
68
+ results.append({"input": case, "python": a, "core": b})
69
+ print(json.dumps(results))
70
+ `;
71
+
72
+ /** A decimal written without trailing zeros: "107.00" → "107", "-0.50" → "-0.5", "1E+2" stays as written. */
73
+ const decimalText = (t) => { const s = String(t); return /^-?\d+\.\d+$/.test(s) ? s.replace(/0+$/, '').replace(/\.$/, '') : s.replace(/^-0$/, '0'); };
74
+
75
+ /** Are two normalized values the same? Gives back { same, tolerance } (tolerance: a float was compared within 1e-9). */
76
+ export function sameValue(a, b) {
77
+ let tolerance = false;
78
+ const eq = (x, y) => {
79
+ if (x && typeof x === 'object' && 'number' in x && y && typeof y === 'object' && 'number' in y) {
80
+ if (decimalText(x.number) === decimalText(y.number)) return true; // the same digits (107.0 and 107.00 are equal)
81
+ const p = Number(x.number), q = Number(y.number);
82
+ if ((x.float || y.float) && Math.abs(p - q) <= 1e-9 * Math.max(1, Math.abs(p), Math.abs(q))) { tolerance = true; return true; }
83
+ return false;
84
+ }
85
+ if (Array.isArray(x) || Array.isArray(y)) return Array.isArray(x) && Array.isArray(y) && x.length === y.length && x.every((v, i) => eq(v, y[i]));
86
+ if (x && y && typeof x === 'object' && typeof y === 'object') {
87
+ const kx = Object.keys(x).sort(), ky = Object.keys(y).sort();
88
+ return kx.join() === ky.join() && kx.every((k) => eq(x[k], y[k]));
89
+ }
90
+ return x === y;
91
+ };
92
+ return { same: eq(a, b), tolerance };
93
+ }
94
+
95
+ /** Printed text compared line by line; a line of numbers matches within the same float tolerance. */
96
+ function samePrinted(a, b) {
97
+ const la = a.split('\n'), lb = b.split('\n');
98
+ if (la.length !== lb.length) return { same: false, tolerance: false };
99
+ let tolerance = false;
100
+ for (let i = 0; i < la.length; i++) {
101
+ if (la[i] === lb[i]) continue;
102
+ const p = Number(la[i]), q = Number(lb[i]);
103
+ if (la[i].trim() && lb[i].trim() && Number.isFinite(p) && Number.isFinite(q) && Math.abs(p - q) <= 1e-9 * Math.max(1, Math.abs(p), Math.abs(q))) { tolerance = true; continue; }
104
+ return { same: false, tolerance };
105
+ }
106
+ return { same: true, tolerance };
107
+ }
108
+
109
+ /**
110
+ * Run the original Python function and the one compiled from its Core on each input.
111
+ * { python: source, core: Thunder Core text, name: python function name, inputs: ['150, True', …] }
112
+ * Gives back { ran, error?, cases: [{ input, same, tolerance, why?, python, core }] }.
113
+ */
114
+ export function verifyRoundTrip({ python, core, name, inputs, coreFunction = null, kind = 'function', cls = null }) {
115
+ const py = findPython();
116
+ if (py.error) return { ran: false, error: `Python 3.10+ is needed to check by running: ${py.error}`, cases: [] };
117
+ const compiled = compileCore(core, { file: `${name}.thunder` });
118
+ if (compiled.diagnostics.length) return { ran: false, error: `The Core does not compile: ${compiled.diagnostics[0].message}`, cases: [] };
119
+ // The compiled function: the def whose "# thunder:N" marks the "To <coreFunction>:" line (else the first def).
120
+ let coreName;
121
+ if (coreFunction) {
122
+ const line = core.split('\n').findIndex((l) => l === `To ${coreFunction}:`) + 1;
123
+ coreName = line ? new RegExp(`^def (\\w+)\\(.*# thunder:${line}$`, 'm').exec(compiled.python)?.[1] : undefined;
124
+ } else coreName = /^def (\w+)\(/m.exec(compiled.python.split('\n').filter((l) => !l.startsWith(' ')).join('\n').replace(/^def (main|_\w+)\(.*$/gm, ''))?.[1];
125
+ if (!coreName) return { ran: false, error: 'The compiled Core has no function to call', cases: [] };
126
+ const dir = mkdtempSync(join(tmpdir(), 'thunder-roundtrip-'));
127
+ try {
128
+ writeFileSync(join(dir, 'original.py'), python);
129
+ writeFileSync(join(dir, 'from_core.py'), compiled.python);
130
+ writeFileSync(join(dir, 'thunder_runtime.py'), PYTHON_RUNTIME);
131
+ writeFileSync(join(dir, 'harness.py'), HARNESS);
132
+ writeFileSync(join(dir, 'plan.json'), JSON.stringify({ python: name, core: coreName, inputs, kind, cls }));
133
+ const r = spawnSync(py.cmd, ['harness.py', 'plan.json'], { cwd: dir, encoding: 'utf8', timeout: 30000, env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1' } });
134
+ if (r.status !== 0) return { ran: false, error: `The check did not run: ${(r.stderr || r.error?.message || '').trim().split('\n').at(-1)}`, cases: [] };
135
+ const cases = JSON.parse(r.stdout).map((c) => {
136
+ const v = sameValue(c.python.value, c.core.value);
137
+ const p = samePrinted(c.python.printed, c.core.printed);
138
+ // The same failure: both stopped, with the same message or the same kind of error (Core's divide-by-zero is a
139
+ // ZeroDivisionError too). The messages may be worded differently; both are shown.
140
+ const pk = c.python.kinds?.[0];
141
+ const err = (c.python.error == null) === (c.core.error == null) && (c.python.error == null || c.core.error.includes(c.python.error) || c.python.error.includes(c.core.error) || (pk && pk !== 'Exception' && (c.core.kinds || []).includes(pk)));
142
+ // A method may change its object: the object afterwards must match too.
143
+ const after = kind === 'method' ? sameValue(c.python.after, c.core.after) : { same: true, tolerance: false };
144
+ const same = v.same && p.same && err && after.same;
145
+ const why = same ? undefined : !err ? `errors differ (Python: ${c.python.error ?? 'none'}; Core: ${c.core.error ?? 'none'})` : !v.same ? 'the values given back differ' : !after.same ? 'the object is different afterwards' : 'what was printed differs';
146
+ return { input: c.input, same, tolerance: v.tolerance || p.tolerance || after.tolerance, ...(why ? { why } : {}), python: c.python, core: c.core };
147
+ });
148
+ return { ran: true, cases };
149
+ } finally { rmSync(dir, { recursive: true, force: true }); }
150
+ }