@skillstech/thunderlang 1.2.0 → 1.3.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 (47) hide show
  1. package/CHANGELOG.md +131 -0
  2. package/dist/core.cjs +2080 -278
  3. package/dist/index.cjs +12742 -10943
  4. package/dist/learn.cjs +2716 -345
  5. package/package.json +1 -1
  6. package/src/cli.mjs +31 -6
  7. package/src/core/ThunderRuntime.cs +1367 -0
  8. package/src/core/check.mjs +158 -2
  9. package/src/core/cli.mjs +148 -8
  10. package/src/core/csharp-run.mjs +184 -0
  11. package/src/core/diagnostics.mjs +13 -1
  12. package/src/core/engine-core.mjs +285 -2
  13. package/src/core/engine-values.mjs +1 -1
  14. package/src/core/format.mjs +191 -3
  15. package/src/core/go-run.mjs +106 -0
  16. package/src/core/index.mjs +2 -1
  17. package/src/core/java/thunder/T.java +6 -0
  18. package/src/core/java/thunder/ThunderRuntime.java +1374 -0
  19. package/src/core/java-run.mjs +89 -0
  20. package/src/core/parser.mjs +331 -5
  21. package/src/core/project.mjs +31 -6
  22. package/src/core/react-run.mjs +96 -0
  23. package/src/core/runtime-go/thunder_runtime.go +3038 -0
  24. package/src/core/runtime-react.mjs +133 -0
  25. package/src/core/rust/thunder_runtime.rs +1645 -0
  26. package/src/core/rust-run.mjs +192 -0
  27. package/src/core/screen-values.mjs +30 -0
  28. package/src/core/target-csharp.mjs +484 -0
  29. package/src/core/target-go.mjs +555 -0
  30. package/src/core/target-java.mjs +587 -0
  31. package/src/core/target-react.mjs +270 -0
  32. package/src/core/target-rust.mjs +534 -0
  33. package/src/core/target-typescript.mjs +2 -2
  34. package/src/core.d.ts +18 -0
  35. package/src/core.mjs +1 -0
  36. package/src/emit.mjs +1 -1
  37. package/src/faithful.mjs +30 -0
  38. package/src/libraries.mjs +10 -3
  39. package/src/model.mjs +50 -8
  40. package/src/read-level.mjs +48 -2
  41. package/src/read-repo-fs.mjs +3 -1
  42. package/src/read.mjs +28 -5
  43. package/src/replay-cli.mjs +123 -0
  44. package/src/say-less.mjs +152 -11
  45. package/src/screens.mjs +833 -0
  46. package/src/steps.mjs +430 -19
  47. package/src/term.mjs +43 -0
@@ -0,0 +1,534 @@
1
+ // Thunder Core -> Rust (a binary crate; standard library only).
2
+ //
3
+ // The same checked program the Python target, the Thunder engine, and the TypeScript target use (compileCore ->
4
+ // program + info), and the same meaning: every statement does what target-typescript.mjs writes for it, and every
5
+ // operation calls thunder_runtime.rs, a line-by-line port of the engine's own value code (engine-values.mjs).
6
+ // compiler/test/core-engines.mjs runs every Core test program on Python, the Thunder engine, compiled TypeScript, and
7
+ // compiled Rust, and requires the same output.
8
+ //
9
+ // Every generated statement sets the frame's line (T::set_line(N)) and ends with `// thunder:N`, the Thunder line it
10
+ // came from, so an error says which Thunder line failed, exactly as the other targets do. An error is a panic
11
+ // carrying the Thunder error; each function's frame (T::call) catches it on the way out and remembers where it was.
12
+
13
+ import { percentDecimal } from './target-python.mjs';
14
+ import { firstLine } from './target-typescript.mjs';
15
+
16
+ /** A Rust string literal for any text. */
17
+ export function rs(s) {
18
+ let out = '"';
19
+ for (const ch of String(s)) {
20
+ const cp = ch.codePointAt(0);
21
+ if (ch === '"') out += '\\"';
22
+ else if (ch === '\\') out += '\\\\';
23
+ else if (ch === '\n') out += '\\n';
24
+ else if (ch === '\r') out += '\\r';
25
+ else if (ch === '\t') out += '\\t';
26
+ else if (cp < 0x20 || cp === 0x7f || (cp >= 0xd800 && cp <= 0xdfff)) out += `\\u{${cp.toString(16)}}`;
27
+ else out += ch;
28
+ }
29
+ return `${out}"`;
30
+ }
31
+
32
+ const RESERVED = new Set(('as async await break const continue crate dyn else enum extern false fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait true type unsafe use where while abstract become box do final macro override priv typeof unsized virtual yield try union T Value FILE main init thunder_tests std core alloc').split(' '));
33
+ /** A Rust name for a Thunder (Python) name: the same, unless Rust or the generated code owns it. */
34
+ export const id = (py) => (RESERVED.has(py) ? `${py}_` : py);
35
+ /** The function that gives a kept value, and the one that gives a record's kind. */
36
+ export const keptFn = (py) => `kept_${py}`;
37
+ export const kindFn = (py) => `kind_${py}`;
38
+
39
+ const KNOWN_BOOL = new Set(['cmp', 'contains', 'between', 'adj', 'isNothing', 'not', 'bool', 'affix']);
40
+
41
+ /** Thunder modules a program uses that only Python has (Use): compiled Rust cannot call them. */
42
+ export function pythonOnlyUses(info) {
43
+ return (info.modules ?? []).filter((m) => !info.imported?.has(m)).map((m) => ({ module: m.module, line: m.line }));
44
+ }
45
+
46
+ /**
47
+ * Compile one checked file. `imports`: [{ module, names }] for a test file (the project's src modules it sees).
48
+ * Gives back the text of the module's .rs file.
49
+ */
50
+ export function toRust(program, info, { source = 'main.thunder', imports = [] } = {}) {
51
+ return new Gen(program, info, source).module(imports);
52
+ }
53
+
54
+ /** The names a src module gives a test module: its record kinds, functions, and kept values. */
55
+ export function exportedRustNames(info) {
56
+ const own = (s) => !info.imported?.has(s);
57
+ return [
58
+ ...info.records.filter(own).map((r) => kindFn(r.py)),
59
+ ...info.funcs.filter(own).map((f) => id(f.py)),
60
+ ...info.consts.filter(own).map((k) => keptFn(k.py)),
61
+ ];
62
+ }
63
+
64
+ class Gen {
65
+ constructor(program, info, source) {
66
+ this.p = program; this.info = info; this.source = source;
67
+ this.out = []; this.ind = 0; this.tmp = 0;
68
+ this.consts = new Set(info.consts.map((k) => k.py));
69
+ this.funcs = new Map(info.funcs.map((f) => [f.py, f]));
70
+ this.tryDepth = 0; // inside "If this fails": a Give leaves through the closure
71
+ this.isVoid = false;
72
+ this.ruleFns = [];
73
+ }
74
+ emit(text, line) { this.out.push(`${' '.repeat(this.ind)}${text}${line ? ` // thunder:${line}` : ''}`); }
75
+ blank() { if (this.out.length && this.out[this.out.length - 1] !== '') this.out.push(''); }
76
+ fresh(base) { return `${base}_${++this.tmp}`; }
77
+
78
+ module(imports) {
79
+ const own = (s) => !this.info.imported?.has(s);
80
+ const head = [
81
+ `// Generated by the Thunder compiler from ${this.source}.`,
82
+ `// A build artifact: change ${this.source.split('/').pop()} and build again, or keep this file and edit it as Rust.`,
83
+ '// It needs only Rust and thunder_runtime.rs (written next to it). "// thunder:N" marks the Thunder line.',
84
+ '#![allow(unused_mut, unused_variables, unused_assignments, unreachable_code, non_snake_case, dead_code, unused_imports, unused_parens, unused_braces, non_upper_case_globals, clippy::all)]',
85
+ '',
86
+ 'use thunder_runtime::{self as T, Value};',
87
+ ...imports.filter((m) => m.names.length).map((m) => `use crate::${m.module}::{${m.names.join(', ')}};`),
88
+ '',
89
+ `const FILE: &str = ${rs(this.source)};`,
90
+ ];
91
+ for (const r of this.info.records.filter(own)) { this.blank(); this.record(r); }
92
+ for (const f of this.info.funcs.filter(own)) { this.blank(); this.func(f); }
93
+ const consts = this.info.consts.filter(own);
94
+ this.blank();
95
+ if (consts.length) {
96
+ this.emit('thread_local! {');
97
+ this.ind++;
98
+ for (const k of consts) this.emit(`static ${this.slot(k.py)}: T::Kept = T::Kept::new();`, k.line);
99
+ this.ind--;
100
+ this.emit('}');
101
+ for (const k of consts) this.emit(`pub fn ${keptFn(k.py)}() -> Value { ${this.slot(k.py)}.with(|k| k.get()) }`, k.line);
102
+ this.blank();
103
+ }
104
+ this.emit('/// Work out this file\'s kept values (before anything runs).');
105
+ this.emit('pub fn init() {');
106
+ this.ind++;
107
+ if (consts.length) {
108
+ this.emit('T::init(FILE, || {');
109
+ this.ind++;
110
+ for (const k of consts) this.emit(`T::set_line(${k.line}); let v = ${this.x(k.e)}; ${this.slot(k.py)}.with(|k| k.set(v));`, k.line);
111
+ this.ind--;
112
+ this.emit('});');
113
+ }
114
+ this.ind--;
115
+ this.emit('}');
116
+ const tests = this.info.tests;
117
+ for (const t of tests) {
118
+ this.blank();
119
+ this.emit(`fn ${id(t.py)}() {`, t.line);
120
+ this.ind++;
121
+ this.frameBody(`T::frame(FILE, ${t.line}`, t.body, [], true);
122
+ this.ind--;
123
+ this.emit('}');
124
+ }
125
+ this.blank();
126
+ this.emit('pub fn thunder_tests() -> Vec<(&\'static str, fn(), i64)> {');
127
+ this.ind++;
128
+ this.emit(`vec![${tests.map((t) => `(${rs(t.title)}, ${id(t.py)} as fn(), ${t.line})`).join(', ')}]`);
129
+ this.ind--;
130
+ this.emit('}');
131
+ const main = this.p.main ?? [];
132
+ this.blank();
133
+ this.emit('pub fn main() {');
134
+ this.ind++;
135
+ if (main.length) this.frameBody('T::frame(FILE, 0', main, [], true);
136
+ this.ind--;
137
+ this.emit('}');
138
+ const rules = this.ruleFns.length ? `\n${this.ruleFns.join('\n')}\n` : '';
139
+ return `${head.join('\n')}\n${this.out.join('\n').replace(/\n{3,}/g, '\n\n')}\n${rules}`;
140
+ }
141
+
142
+ slot(py) { return `KEPT_${py.toUpperCase()}`; }
143
+
144
+ record(r) {
145
+ const fields = r.fields.map((f) => `(${rs(f.py)}, ${rs(f.type?.k ?? 'any')})`).join(', ');
146
+ const rules = r.rulesToCheck ?? [];
147
+ const bySubject = new Map();
148
+ for (const rule of rules) { const f = r.fieldMap.get(rule.subject); (bySubject.get(f.py) ?? bySubject.set(f.py, []).get(f.py)).push(rule); }
149
+ const ruleCode = [...bySubject].map(([field, rs_]) => `(${rs(field)}, vec![${rs_.map((rule) => {
150
+ const fn = this.ruleFn(`rule_${r.py}_${field}_${rule.line}_${++this.tmp}`, rule.rule.cond);
151
+ return `T::Rule { cond: ${fn}, text: ${rs(rule.text)}, line: ${rule.line} }`;
152
+ }).join(', ')}])`).join(', ');
153
+ this.emit('thread_local! {', r.line);
154
+ this.ind++;
155
+ this.emit(`static KIND_${r.py.toUpperCase()}: std::rc::Rc<T::Kind> = T::kind(${rs(r.py)}, vec![${fields}], vec![${ruleCode}]);`, r.line);
156
+ this.ind--;
157
+ this.emit('}');
158
+ this.emit(`/// The ${r.py} record: its fields${rules.length ? ' and the rules they must keep' : ''}.`);
159
+ this.emit(`pub fn ${kindFn(r.py)}() -> std::rc::Rc<T::Kind> { KIND_${r.py.toUpperCase()}.with(|k| k.clone()) }`, r.line);
160
+ }
161
+
162
+ /** A Never rule's condition as a function of the new value. */
163
+ ruleFn(name, cond) {
164
+ const saved = { tryDepth: this.tryDepth };
165
+ const body = this.x(cond, { subject: 'value.clone()' });
166
+ Object.assign(this, saved);
167
+ this.ruleFns.push(`fn ${name}(value: Value) -> Value { ${body} }`);
168
+ return name;
169
+ }
170
+
171
+ func(f) {
172
+ const params = f.params.map((p) => `${id(p.py)}: Value`);
173
+ this.emit(`pub fn ${id(f.py)}(${params.join(', ')}) -> Value {`, f.line);
174
+ this.ind++;
175
+ const pre = [];
176
+ for (const p of f.params) pre.push([`let mut ${id(p.py)} = ${id(p.py)};`, null]);
177
+ for (const p of f.params) if (p.dflt?.k === 'name') pre.push([`if matches!(${id(p.py)}, Value::NotGiven) { T::set_line(${p.line}); ${id(p.py)} = ${this.x(p.dflt)}; }`, p.line]);
178
+ for (const p of f.params) for (const rule of p.rules ?? []) pre.push([`T::set_line(${p.line}); T::never(${this.x(rule.rule.cond, { subject: `${id(p.py)}.clone()` })}, ${rs(rule.text)}, ${rule.line}, ${id(p.py)}.clone());`, p.line]);
179
+ const first = firstLine(f);
180
+ this.frameBody(`T::call(FILE, ${f.line}, ${first == null ? 'None' : `Some(${first})`}`, f.body, pre, false, f.params.map((p) => p.py));
181
+ this.ind--;
182
+ this.emit('}');
183
+ }
184
+
185
+ /** A body that runs in its own frame: errors leave with the Thunder line they happened on. */
186
+ frameBody(enter, body, pre, isVoid, params = []) {
187
+ const savedVoid = this.isVoid;
188
+ this.isVoid = isVoid;
189
+ this.emit(`${enter}, move || {`);
190
+ this.ind++;
191
+ const locals = [...this.localsOf(body)].filter((n) => !params.includes(n));
192
+ for (const n of locals) this.emit(`let mut ${id(n)}: Value = T::NOTHING;`);
193
+ for (const [code, line] of pre) this.emit(code, line);
194
+ this.block(body);
195
+ if (!isVoid) this.emit('T::NOTHING');
196
+ this.ind--;
197
+ this.emit(isVoid ? '});' : '})');
198
+ this.isVoid = savedVoid;
199
+ }
200
+
201
+ /** The names a body assigns (Python's locals): declared once at the top, as a Python function's are. */
202
+ localsOf(body) {
203
+ const names = new Set();
204
+ const visit = (ss) => {
205
+ for (const s of ss ?? []) {
206
+ if (s.k === 'set' && s.target.k === 'name' && s.target.ref?.py) names.add(s.target.ref.py);
207
+ for (const v of s.vars ?? []) if (v?.py) names.add(v.py);
208
+ if (s.k === 'range' && s.v?.py) names.add(s.v.py);
209
+ if (s.errPy) names.add(s.errPy);
210
+ visit(s.body); visit(s.handler); visit(s.otherwise);
211
+ for (const b of s.branches ?? []) visit(b.body);
212
+ if (s.stmt) visit([s.stmt]);
213
+ }
214
+ };
215
+ visit(body);
216
+ const globals = new Set([...this.info.consts, ...this.info.funcs, ...this.info.records].map((x) => x.py));
217
+ return [...names].filter((n) => !globals.has(n));
218
+ }
219
+
220
+ block(body) { for (const s of body) this.stmt(s); }
221
+
222
+ /** T::set_line(N); <code> // thunder:N */
223
+ line(L, code) { this.emit(`T::set_line(${L}); ${code}`, L); }
224
+
225
+ /** Give: leave the function (or, inside "If this fails", the closure that catches the failure). */
226
+ giveCode(value) {
227
+ if (this.tryDepth > 0) return `return Some(${this.isVoid ? 'T::NOTHING' : value});`;
228
+ return this.isVoid ? 'return;' : `return ${value};`;
229
+ }
230
+
231
+ /** Check a watched name's Never rules on its new value, then store it. */
232
+ assign(s, name, valueCode) {
233
+ if (!s.rules?.length) { this.line(s.line, `${id(name)} = ${valueCode};`); return; }
234
+ const v = this.fresh('new');
235
+ this.line(s.line, `{ let ${v} = ${valueCode};`);
236
+ this.ind++;
237
+ for (const rule of s.rules) this.emit(`T::never(${this.x(rule.rule.cond, { subject: `${v}.clone()` })}, ${rs(rule.text)}, ${rule.line}, ${v}.clone());`, s.line);
238
+ this.emit(`${id(name)} = ${v}; }`, s.line);
239
+ this.ind--;
240
+ }
241
+ rulesAfter(s, name) {
242
+ for (const rule of s.rules ?? []) this.emit(`T::never(${this.x(rule.rule.cond, { subject: `${id(name)}.clone()` })}, ${rs(rule.text)}, ${rule.line}, ${id(name)}.clone());`, s.line);
243
+ }
244
+
245
+ /** Code that stores `v` (a Rust variable holding the value) into a name, a field, or an entry. */
246
+ storeCode(t, v) {
247
+ if (t.k === 'name') return `${id(t.ref?.py ?? 'unknown')} = ${v};`;
248
+ if (t.k === 'field') return t.static ? `T::set_attr(${this.x(t.obj)}, ${rs(t.py)}, ${v});` : `T::set_field(${this.x(t.obj)}, ${rs(t.text)}, ${v});`;
249
+ if (t.k === 'at') {
250
+ const fn = t.objKind === 'list' ? 'T::set_item' : t.objKind === 'map' ? 'T::map_set' : 'T::set_entry';
251
+ return `${fn}(${this.x(t.obj)}, ${this.x(t.key)}, ${v});`;
252
+ }
253
+ return '';
254
+ }
255
+
256
+ stmt(s) {
257
+ const L = s.line;
258
+ switch (s.k) {
259
+ case 'say': this.line(L, `T::say(${s.e.type?.k === 'text' ? `T::py_str(${this.x(s.e)})` : `T::show(${this.x(s.e)})`});`); return;
260
+ case 'set': {
261
+ const t = s.target;
262
+ if (t.k === 'name') { this.assign(s, t.ref.py, this.x(s.e)); return; }
263
+ const v = this.fresh('v');
264
+ this.line(L, `{ let ${v} = ${this.x(s.e)}; ${this.storeCode(t, v)} }`);
265
+ return;
266
+ }
267
+ case 'give': this.line(L, this.giveCode(s.e.k === 'nothing' ? 'T::NOTHING' : this.x(s.e))); return;
268
+ case 'stop': { const v = this.x(s.e); this.line(L, `T::stop_with(${s.e.type?.k === 'text' ? `T::py_str(${v})` : `T::show(${v})`});`); return; }
269
+ case 'if': {
270
+ this.emit(`T::set_line(${L});`, L);
271
+ s.branches.forEach((b, k) => {
272
+ this.emit(`${k === 0 ? 'if' : '} else if'} { T::set_line(${b.line}); ${this.yn(b.cond)} } {`, b.line);
273
+ this.ind++; this.block(b.body); this.ind--;
274
+ });
275
+ if (s.otherwise) { this.emit('} else {'); this.ind++; this.block(s.otherwise); this.ind--; }
276
+ this.emit('}');
277
+ return;
278
+ }
279
+ case 'each': {
280
+ const [a, b] = s.vars;
281
+ const it = this.x(s.iter);
282
+ const seq = b ? (s.iterKind === 'map' ? `T::map_items(${it})` : s.iterKind === 'pairs' ? `T::py_iter(${it})` : `T::pairs_of(${it})`) : `T::py_iter(${it})`;
283
+ const el = this.fresh('el');
284
+ this.line(L, `for ${el} in ${seq} {`);
285
+ this.ind++;
286
+ if (b) { const p = this.fresh('pair'); this.emit(`T::set_line(${L}); let ${p} = T::unpack2(${el}); ${id(a.py)} = ${p}.0; ${id(b.py)} = ${p}.1;`, L); }
287
+ else this.emit(`T::set_line(${L}); ${id(a.py)} = ${el};`, L);
288
+ this.block(s.body);
289
+ this.ind--;
290
+ this.emit('}');
291
+ return;
292
+ }
293
+ case 'range': {
294
+ const lo = this.fresh('from'), hi = this.fresh('to'), n = this.fresh('n');
295
+ const to = s.to.k === 'num' && s.to.whole ? `T::int(${rs(String(BigInt(s.to.text.replace(/_/g, '')) + 1n))})` : `T::add(${this.x(s.to)}, T::int_n(1))`;
296
+ const a = this.fresh('a'), b = this.fresh('b');
297
+ this.line(L, `{ let ${a} = ${this.x(s.from)}; let ${b} = ${to}; let ${lo} = T::range_int(${a}); let ${hi} = T::range_int(${b});`);
298
+ this.ind++;
299
+ this.emit(`for ${n} in ${lo}..${hi} {`);
300
+ this.ind++;
301
+ this.emit(`T::set_line(${L}); ${id(s.v.py)} = T::int_n(${n});`, L);
302
+ this.block(s.body);
303
+ this.ind--;
304
+ this.emit('}');
305
+ this.ind--;
306
+ this.emit('}');
307
+ return;
308
+ }
309
+ case 'while':
310
+ this.emit(`while { T::set_line(${L}); ${s.until ? `!${this.yn(s.cond)}` : this.yn(s.cond)} } {`, L);
311
+ this.ind++; this.block(s.body); this.ind--;
312
+ this.emit('}');
313
+ return;
314
+ case 'times': {
315
+ const count = this.fresh('count'), k = this.fresh('k');
316
+ this.line(L, `{ let ${count} = T::range_int(${this.x(s.count)});`);
317
+ this.ind++;
318
+ this.emit(`for ${k} in 0..${count} {`);
319
+ this.ind++;
320
+ this.emit(`T::set_line(${L});`, L);
321
+ this.block(s.body);
322
+ this.ind--;
323
+ this.emit('}');
324
+ this.ind--;
325
+ this.emit('}');
326
+ return;
327
+ }
328
+ case 'expect': this.expect(s); return;
329
+ case 'add': case 'remove': this.addRemove(s); return;
330
+ case 'increase': case 'decrease': {
331
+ const op = s.k === 'increase' ? 'T::add' : 'T::sub';
332
+ if (s.target.k === 'name') { const py = s.target.ref?.py ?? 'unknown'; this.assign(s, py, `${op}(${this.nameRef(py, s.target.ref)}, ${this.x(s.e)})`); return; }
333
+ const v = this.fresh('v');
334
+ this.line(L, `{ let ${v} = ${op}(${this.x(s.target)}, ${this.x(s.e)}); ${this.storeCode(s.target, v)} }`);
335
+ return;
336
+ }
337
+ case 'sort': {
338
+ const key = s.field ? `Some(T::key_with(Box::new(|item: Value| ${this.fieldGet('item', s.field)})))` : 'None';
339
+ this.line(L, `T::sort_in_place(${this.x(s.target)}, ${key}, ${!!s.desc});`);
340
+ return;
341
+ }
342
+ case 'reverse': this.line(L, `T::reverse_in_place(${this.x(s.target)});`); return;
343
+ case 'do': this.line(L, `${this.x(s.e)};`); return;
344
+ case 'tryFail': {
345
+ const r = this.fresh('tried'), e = this.fresh('failure');
346
+ this.emit(`let ${r} = T::catch(|| -> Option<Value> {`, L);
347
+ this.ind++;
348
+ this.tryDepth++;
349
+ this.stmt(s.stmt);
350
+ this.tryDepth--;
351
+ this.emit('None');
352
+ this.ind--;
353
+ this.emit('});', L);
354
+ this.emit(`match ${r} {`, L);
355
+ this.ind++;
356
+ this.emit(`Ok(Some(given)) => { ${this.tryDepth > 0 ? 'return Some(given);' : this.isVoid ? 'return;' : 'return given;'} }`);
357
+ this.emit('Ok(None) => {}');
358
+ this.emit(`Err(${e}) => {`);
359
+ this.ind++;
360
+ this.line(L, `${id(s.errPy)} = T::explain(${e});`);
361
+ this.block(s.handler);
362
+ this.ind--;
363
+ this.emit('}');
364
+ this.ind--;
365
+ this.emit('}');
366
+ return;
367
+ }
368
+ default: this.emit(`// not generated: ${s.k}`, L);
369
+ }
370
+ }
371
+
372
+ addRemove(s) {
373
+ const L = s.line;
374
+ const isName = s.target.k === 'name';
375
+ const py = isName ? s.target.ref?.py ?? 'unknown' : null;
376
+ const v = this.fresh('v'), t = this.fresh('t');
377
+ const head = `let ${v} = ${this.x(s.e)}; let ${t} = ${this.x(s.target)};`;
378
+ let body;
379
+ if (s.targetKind === 'list') body = s.k === 'add' ? `T::append_to(${t}, ${v});` : `T::remove_from(${t}, ${v});`;
380
+ else if (s.targetKind === 'map') body = `T::remove_from(${t}, ${v});`;
381
+ else if (s.targetKind === 'number') {
382
+ const nv = `${s.k === 'add' ? 'T::add' : 'T::sub'}(${t}, ${v})`;
383
+ if (isName && s.rules?.length) {
384
+ const n = this.fresh('new');
385
+ this.line(L, `{ ${head} let ${n} = ${nv};`);
386
+ this.ind++;
387
+ for (const rule of s.rules) this.emit(`T::never(${this.x(rule.rule.cond, { subject: `${n}.clone()` })}, ${rs(rule.text)}, ${rule.line}, ${n}.clone());`, L);
388
+ this.emit(`${id(py)} = ${n}; }`, L);
389
+ this.ind--;
390
+ this.rulesAfter(s, py);
391
+ return;
392
+ }
393
+ body = isName ? `${id(py)} = ${nv};` : this.storeCode(s.target, nv);
394
+ } else if (s.k === 'add') body = isName ? `${id(py)} = T::add_to(${t}, ${v});` : this.storeCode(s.target, `T::add_to(${t}, ${v})`);
395
+ else body = `T::remove_from(${t}, ${v});`;
396
+ this.line(L, `{ ${head} ${body} }`);
397
+ if (isName) this.rulesAfter(s, py);
398
+ }
399
+
400
+ expect(s) {
401
+ const L = s.line;
402
+ const text = rs((s.raw ?? 'Expect').trim());
403
+ if (s.mode === 'true') { this.line(L, `T::expect_true(${this.x(s.e)}, ${text});`); return; }
404
+ if (s.mode === 'fail') {
405
+ const m = this.fresh('msg');
406
+ this.line(L, `{ let ${m} = ${s.msg ? this.x(s.msg) : 'T::NOTHING'}; T::expect_failure(|| { ${this.x(s.e)}; }, ${text}, ${m}); }`);
407
+ return;
408
+ }
409
+ if (s.mode === 'cmp') { this.line(L, `T::expect_value(${this.x(s.e)}, "contains", "contains", ${this.x(s.want)}, ${text});`); return; }
410
+ let c = s.check, negate = false;
411
+ if (c.k === 'not') { negate = true; c = c.e; }
412
+ const OPS = { '==': 'is', '!=': 'is not', '>=': 'at least', '<=': 'at most', '>': 'more than', '<': 'less than' };
413
+ let op, want = 'T::NOTHING';
414
+ if (c.k === 'cmp') { op = OPS[c.op]; want = this.x(c.r); }
415
+ else if (c.k === 'adj') op = c.adj;
416
+ else if (c.k === 'isNothing') op = c.neg ? 'not nothing' : 'nothing';
417
+ else if (c.k === 'between') { op = 'between'; want = `T::list(vec![${this.x(c.lo)}, ${this.x(c.hi)}])`; }
418
+ else if (c.k === 'contains') { op = 'in'; want = this.x(c.l); }
419
+ else op = 'is';
420
+ this.line(L, `T::expect_value(${this.x(s.e)}, ${rs(negate ? `not ${op}` : op)}, ${rs(op)}, ${want}, ${text});`);
421
+ }
422
+
423
+ fieldGet(v, field) { return field.dynamic ? `T::get_field(${v}, ${rs(field.key)})` : `T::get_attr(${v}, ${rs(field.py)})`; }
424
+
425
+ /** A value used as yes/no: a Rust bool, checked when the program runs. */
426
+ yn(e, ctx = {}) { return `T::yes_no(${this.x(e, ctx)})`; }
427
+
428
+ /** A name's value: a kept value comes from its slot; a local or an input is cloned (values are shared, like Python's). */
429
+ nameRef(py, ref) {
430
+ if (ref?.kind === 'const' || (this.consts.has(py) && ref?.kind !== 'var' && ref?.kind !== 'param')) return `${keptFn(py)}()`;
431
+ return `${id(py)}.clone()`;
432
+ }
433
+
434
+ /** A call to a Thunder function, with the inputs it leaves out filled in (as Python's defaults do). */
435
+ callCode(e, sub) {
436
+ const f = this.funcs.get(e.py);
437
+ const args = e.args.map(sub);
438
+ if (f && args.length < f.params.length) {
439
+ for (const p of f.params.slice(args.length)) args.push(p.dflt?.k === 'name' ? 'T::NOT_GIVEN' : p.dflt ? this.x(p.dflt) : 'T::NOTHING');
440
+ }
441
+ return `${id(e.py)}(${args.join(', ')})`;
442
+ }
443
+
444
+ x(e, ctx = {}) {
445
+ const sub = (k) => this.x(k, ctx);
446
+ switch (e.k) {
447
+ case 'num': return e.whole ? `T::int(${rs(String(BigInt(e.text.replace(/_/g, ''))))})` : `T::dec(${rs(e.text)})`;
448
+ case 'money': return `T::money(${rs(e.text)})`;
449
+ case 'percent': return `T::dec(${rs(percentDecimal(e.text))})`;
450
+ case 'bool': return `T::yes(${e.v ? 'true' : 'false'})`;
451
+ case 'nothing': case 'hole': return 'T::NOTHING';
452
+ case 'paren': return sub(e.e);
453
+ case 'today': return 'T::today()';
454
+ case 'date': return `T::date(${rs(e.text)})`;
455
+ case 'str': return this.str(e, ctx);
456
+ case 'list': return e.items ? `T::list(vec![${e.items.map(sub).join(', ')}])` : 'T::new_map()';
457
+ case 'map': return 'T::new_map()';
458
+ case 'name': {
459
+ const r = e.ref ?? {};
460
+ if (r.kind === 'subject') return ctx.subject ?? 'T::NOTHING';
461
+ if (r.kind === 'elemField') return `T::get_attr(${ctx.item}, ${rs(r.py)})`;
462
+ if (r.kind === 'elemKey') return `T::get_field(${ctx.item}, ${rs(r.key)})`;
463
+ if (r.kind === 'elem') return ctx.item;
464
+ return this.nameRef(r.py ?? e.name.replace(/ /g, '_'), r);
465
+ }
466
+ case 'call': return this.callCode(e, sub);
467
+ case 'new': return `T::new_record(${kindFn(e.py)}(), vec![${e.fields.map((f) => `(${rs(f.py)}, ${sub(f.e)})`).join(', ')}])`;
468
+ case 'field': return e.static ? `T::get_attr(${sub(e.obj)}, ${rs(e.py)})` : `T::get_field(${sub(e.obj)}, ${rs(e.text)})`;
469
+ case 'at': {
470
+ const fn = e.objKind === 'map' ? 'T::map_get' : e.objKind === 'list' ? 'T::item_at' : 'T::entry';
471
+ return `${fn}(${sub(e.obj)}, ${sub(e.key)}, ${e.dflt ? `Some(${sub(e.dflt)})` : 'None'})`;
472
+ }
473
+ case 'conv': {
474
+ const fn = { list: 'T::py_list', number: 'T::to_number', whole: 'T::to_whole', money: 'T::to_money', text: 'T::show', bool: 'T::to_yes_no', date: 'T::to_date' }[e.to];
475
+ return fn ? `${fn}(${sub(e.e)})` : sub(e.e);
476
+ }
477
+ case 'where': {
478
+ const v = this.fresh('item');
479
+ return `T::list(T::py_iter(${sub(e.list)}).into_iter().filter(|${v}: &Value| T::truthy(&${this.x(e.cond, { ...ctx, item: `${v}.clone()` })})).collect())`;
480
+ }
481
+ case 'from': {
482
+ const inner = e.list.k === 'where' ? e.list : null;
483
+ const v = this.fresh('item');
484
+ const list = `T::py_iter(${sub(inner ? inner.list : e.list)}).into_iter()`;
485
+ const filtered = inner ? `${list}.filter(|${v}: &Value| T::truthy(&${this.x(inner.cond, { ...ctx, item: `${v}.clone()` })}))` : list;
486
+ return `T::list(${filtered}.map(|${v}: Value| ${this.fieldGet(v, e.field)}).collect())`;
487
+ }
488
+ case 'sorted': {
489
+ if (e.mapSort) return `T::py_sort(T::list(T::map_items(${sub(e.list)})), Some(T::key_with(Box::new(|entry: Value| T::tuple_at(entry, ${e.by === 'key' ? 0 : 1})))), ${!!e.desc})`;
490
+ return `T::py_sort(T::py_list(${sub(e.list)}), Some(T::key_with(Box::new(|item: Value| ${this.fieldGet('item', e.field)}))), ${!!e.desc})`;
491
+ }
492
+ case 'op': return `T::apply_op(${rs(e.op)}, ${sub(e.arg)})`;
493
+ case 'round': return `T::round_to(${sub(e.e)}, ${e.places ? sub(e.places) : 'T::int_n(0)'})`;
494
+ case 'readFile': return `T::read_text(${sub(e.path)})`;
495
+ case 'neg': return `T::neg(${sub(e.e)})`;
496
+ case 'not': return `T::yes(!${this.yn(e.e, ctx)})`;
497
+ case 'bin': {
498
+ if (e.op === 'and') return `T::yes(${this.yn(e.l, ctx)} && ${this.yn(e.r, ctx)})`;
499
+ if (e.op === 'or') return `T::yes(${this.yn(e.l, ctx)} || ${this.yn(e.r, ctx)})`;
500
+ const fn = { '+': 'T::add', '-': 'T::sub', '*': 'T::mul', '/': 'T::divide' }[e.op]
501
+ ?? (e.op === 'mod' ? (e.l.type?.k === 'whole' && e.r.type?.k === 'whole' ? 'T::int_mod' : 'T::modulo') : null);
502
+ return fn ? `${fn}(${sub(e.l)}, ${sub(e.r)})` : 'T::NOTHING';
503
+ }
504
+ case 'cmp': {
505
+ if (e.r.k === 'bool' && (e.op === '==' || e.op === '!=')) return `T::yes(${this.yn(e.l, ctx)} ${e.op === '==' ? '==' : '!='} ${e.r.v ? 'true' : 'false'})`;
506
+ return `T::compare(${rs(e.op)}, ${sub(e.l)}, ${sub(e.r)})`;
507
+ }
508
+ case 'between': return `T::between(${sub(e.lo)}, ${sub(e.e)}, || ${sub(e.hi)})`;
509
+ case 'contains': return `T::is_in(${sub(e.r)}, ${sub(e.l)})`;
510
+ case 'affix': return `T::affix(${sub(e.l)}, ${sub(e.r)}, ${!!e.end})`;
511
+ case 'sortedValues': return `T::py_sort(T::py_list(${sub(e.list)}), None, ${!!e.desc})`;
512
+ case 'joined': return `T::joined(${sub(e.list)}, ${sub(e.sep)})`;
513
+ case 'splitAt': return `T::split_at(${sub(e.text)}, ${sub(e.sep)})`;
514
+ case 'replacing': return `T::replacing(${sub(e.text)}, ${sub(e.from)}, ${sub(e.to)})`;
515
+ case 'adj': {
516
+ if (e.adj === 'empty') return `T::eq(T::len_of(${sub(e.e)}), T::int_n(0))`;
517
+ return `T::compare(${rs({ positive: '>', negative: '<', zero: '==' }[e.adj])}, ${sub(e.e)}, T::int_n(0))`;
518
+ }
519
+ case 'isNothing': return `T::yes(${e.neg ? '!' : ''}T::is_nothing(${sub(e.e)}))`;
520
+ default: return `T::NOTHING /* not generated: ${e.k} */`;
521
+ }
522
+ }
523
+
524
+ /** Text with {holes}: text and whole numbers as they are, anything else shown the Thunder way. */
525
+ str(e, ctx) {
526
+ const parts = e.parts.filter((p) => p !== '').map((p) => {
527
+ if (typeof p === 'string') return `T::text(${rs(p)})`;
528
+ const t = p.e.type?.k;
529
+ return t === 'text' || t === 'whole' ? `T::py_str(${this.x(p.e, ctx)})` : `T::show(${this.x(p.e, ctx)})`;
530
+ });
531
+ if (!parts.length) return 'T::text("")';
532
+ return parts.length === 1 && parts[0].startsWith('T::text(') ? parts[0] : `T::cat(vec![${parts.join(', ')}])`;
533
+ }
534
+ }
@@ -22,7 +22,7 @@ export function firstLine(f) {
22
22
 
23
23
  const js = (s) => JSON.stringify(s); // a valid JS string literal for any text
24
24
 
25
- const RESERVED = new Set(('break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await arguments eval undefined NaN Infinity T F FILE main').split(' '));
25
+ const RESERVED = new Set(('break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await arguments eval undefined NaN Infinity T F FILE main props').split(' '));
26
26
  /** A JavaScript name for a Thunder (Python) name: the same, unless JavaScript or the generated code owns it. */
27
27
  export const id = (py) => (RESERVED.has(py) ? `${py}_` : py);
28
28
 
@@ -51,7 +51,7 @@ export function pythonOnlyUses(info) {
51
51
  return (info.modules ?? []).filter((m) => !info.imported?.has(m)).map((m) => ({ module: m.module, line: m.line }));
52
52
  }
53
53
 
54
- class Gen {
54
+ export class Gen {
55
55
  constructor(program, info, source) {
56
56
  this.p = program; this.info = info; this.source = source;
57
57
  this.out = []; this.ind = 0; this.tmp = 0;
package/src/core.d.ts CHANGED
@@ -17,6 +17,24 @@ export { EXPR_SCHEMA, RENDER_LANGUAGES, parseExpr, parseStatement, renderExpr, r
17
17
  export type { Expr } from './meaning.mjs';
18
18
  export { VISUAL_SCHEMA, THUNDER_VISUAL, LEVELS, PLACES, visualFor, visualForStep, thunderText, thunderTokens } from './visual.mjs';
19
19
  export { MODEL_SCHEMA, THING_LANGUAGES, thunderModel, modelText, readLevel, flowOf, ruleFlow, askAsQuestion, stepDoes, pathsOf } from './model.mjs';
20
+ /** A React or Angular component read as a screen (src/screens.mjs). */
21
+ export interface Screen {
22
+ id: string; kind: 'screen'; framework: 'react' | 'angular'; name: string; label: string; file: string; lines: [number, number];
23
+ selector?: string; template?: string; member?: string; thing?: string;
24
+ inputs: Array<{ name: string; label: string; kind?: string; optional?: boolean; required?: boolean; start?: string; callback?: boolean }>;
25
+ state: Array<{ name: string; label: string; start?: string; how: string; line?: number }>;
26
+ shows: ScreenLine[]; early?: Array<{ when: string; shows: ScreenLine[]; line?: number }>;
27
+ events: Array<{ on: string; event: string; when: string; runs: string; line?: number; member?: string; file?: string }>;
28
+ effects: Array<{ when: string; runs: string; line?: number; member?: string }>;
29
+ outputs: Array<{ name: string; label: string; line?: number }>; services?: string[];
30
+ uses: Array<{ id?: string; label: string; outside?: boolean }>; usedBy?: Array<{ id: string; label: string }>;
31
+ notRead: Array<{ line?: number; code: string; why: string; file?: string }>;
32
+ /** page: a Next.js page file or a component a router opens; top: no other screen shows it; part: shown inside another. */
33
+ role?: 'page' | 'top' | 'part'; roleWhy?: string;
34
+ }
35
+ export interface ScreenLine { says: string; line?: number; kids?: ScreenLine[]; otherwise?: { says: string; line?: number; kids: ScreenLine[] }; notRead?: boolean; /** for a not-read line: the code, without the "not read:" words */ code?: string }
36
+ export function readScreens(files: Array<{ path: string; source: string }>, options?: { members?: unknown[] }): Screen[];
37
+ export function screenText(screen: Screen): string;
20
38
  export { RUNNING_SCHEMA, runtimeOverlay, runtimeText, explainError, parseStack, parseStacks, fromTrace, fromStack, fromLogs, fromOtlp, nodeNote } from './running.mjs';
21
39
  export type { RunEvent, RuntimeOverlay, MemberRun, NodeRun, ParsedStack, ErrorExplanation } from './running.mjs';
22
40
  export { linkSystem, callsSummary, areaOf } from './system.mjs';
package/src/core.mjs CHANGED
@@ -15,6 +15,7 @@ export { WRITE_STEPS_SCHEMA, WRITE_STEPS_LANGUAGES, EDIT_OPS, thunderWrite, prov
15
15
  export { EXPR_SCHEMA, RENDER_LANGUAGES, parseExpr, parseStatement, renderExpr, renderStatement, sayFull, detailParts, detailOf, exprCounts, normalizeExpr, sameExpr, wordsAgree } from './meaning.mjs';
16
16
  export { VISUAL_SCHEMA, THUNDER_VISUAL, LEVELS, PLACES, visualFor, visualForStep, thunderText, thunderTokens } from './visual.mjs';
17
17
  export { MODEL_SCHEMA, THING_LANGUAGES, thunderModel, modelText, readLevel, flowOf, ruleFlow, askAsQuestion, stepDoes, pathsOf } from './model.mjs';
18
+ export { readScreens, screenText } from './screens.mjs';
18
19
  // The running system (browser-safe): runs, stack traces, logs, and spans placed on Thunder's flows.
19
20
  export { RUNNING_SCHEMA, runtimeOverlay, runtimeText, explainError, parseStack, parseStacks, fromTrace, fromStack, fromLogs, fromOtlp, nodeNote } from './running.mjs';
20
21
  export { linkSystem, callsSummary, areaOf } from './system.mjs';
package/src/emit.mjs CHANGED
@@ -30,7 +30,7 @@ export function notesSummary(ast) {
30
30
  };
31
31
  }
32
32
 
33
- export const COMPILER_VERSION = '1.2.0';
33
+ export const COMPILER_VERSION = '1.3.0';
34
34
  export const PROOF_SCHEMA_VERSION = '0.1.0';
35
35
  // Identifies which ecosystem product emitted this proof. Consumed by SkillsTech
36
36
  // Certified to key cert proofs to the compiler. Stable slug per the coordination bus.
package/src/faithful.mjs CHANGED
@@ -135,3 +135,33 @@ export function accountsFor(code, said, tree = null) {
135
135
  export const asCodeWords = (code, n = 120) => { const t = String(code).replace(/\s+/g, ' ').trim(); return `\`${t.length > n ? `${t.slice(0, n - 1)}…` : t}\``; };
136
136
  /** True when a condition's words are the code itself (the gate fell back). */
137
137
  export const isCodeWords = (said) => /^`[^]*`$/.test(String(said).trim());
138
+
139
+ /** A Python import in words (the reader's form in steps.mjs, checked by say-less): null when it is not one plain import. */
140
+ export function pythonImportSays(code) {
141
+ const t = String(code).trim().replace(/\s*#.*$/, '');
142
+ const named = (x) => { const m = /^([A-Za-z_]\w*)(?:\s+as\s+([A-Za-z_]\w*))?$/.exec(x.trim()); return m ? (m[2] && m[2] !== m[1] ? `${m[1]} (called ${m[2]} here)` : m[1]) : null; };
143
+ const list = (xs) => (xs.length <= 1 ? xs.join('') : `${xs.slice(0, -1).join(', ')} and ${xs.at(-1)}`);
144
+ let m;
145
+ if ((m = /^import\s+([A-Za-z_][\w.]*)(?:\s+as\s+([A-Za-z_]\w*))?$/.exec(t))) return `Loads the ${m[1]} module${m[2] && m[2] !== m[1] ? `, called ${m[2]} here` : ''}`;
146
+ if ((m = /^from\s+(\.?)([A-Za-z_][\w.]*)?\s+import\s+\(?([^()*]+?)\)?$/.exec(t))) {
147
+ const names = m[3].split(',').map((x) => x.trim()).filter(Boolean).map(named);
148
+ if (!names.length || names.some((x) => !x) || (!m[1] && !m[2])) return null;
149
+ const from = m[1] ? (m[2] ? `the ${m[2]} module in this package` : 'this package') : `the ${m[2]} module`;
150
+ return `Loads ${list(names)} from ${from}`;
151
+ }
152
+ return null;
153
+ }
154
+
155
+ /**
156
+ * A Python slice (or the last item) in words, `{x}` standing for the list: `[1:]` "{x} without the first 1", `[:3]`
157
+ * "the first 3 of {x}", `[-2:]` "the last 2 of {x}", `[:-1]` "{x} without the last 1", `[-1]` "the last of {x}". Null
158
+ * for anything else (both ends, a step, or a name for an end). Used by the reader and by say-less's check.
159
+ */
160
+ export function sliceWords(start, end, single) {
161
+ if (single != null) return single === '-1' ? 'the last of {x}' : null;
162
+ const n = (x) => (x == null || x === '' ? null : Number(x));
163
+ const a = n(start), b = n(end);
164
+ if (a != null && b == null) return a > 0 ? `{x} without the first ${a}` : a < 0 ? `the last ${-a} of {x}` : null;
165
+ if (a == null && b != null) return b > 0 ? `the first ${b} of {x}` : b < 0 ? `{x} without the last ${-b}` : null;
166
+ return null;
167
+ }