@skillstech/thunderlang 1.1.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 (61) hide show
  1. package/CHANGELOG.md +212 -0
  2. package/README.md +4 -1
  3. package/dist/core.cjs +2080 -278
  4. package/dist/index.cjs +12742 -10943
  5. package/dist/learn.cjs +12976 -3598
  6. package/package.json +2 -2
  7. package/src/cli-home.mjs +242 -0
  8. package/src/cli.mjs +135 -41
  9. package/src/core/ThunderRuntime.cs +1367 -0
  10. package/src/core/check.mjs +158 -2
  11. package/src/core/cli.mjs +208 -17
  12. package/src/core/csharp-run.mjs +184 -0
  13. package/src/core/diagnostics.mjs +13 -0
  14. package/src/core/engine-core.mjs +855 -0
  15. package/src/core/engine-values.mjs +1054 -0
  16. package/src/core/engine-worker.mjs +15 -0
  17. package/src/core/engine.mjs +63 -0
  18. package/src/core/format.mjs +191 -3
  19. package/src/core/go-run.mjs +106 -0
  20. package/src/core/index.mjs +3 -1
  21. package/src/core/java/thunder/T.java +6 -0
  22. package/src/core/java/thunder/ThunderRuntime.java +1374 -0
  23. package/src/core/java-run.mjs +89 -0
  24. package/src/core/parser.mjs +331 -5
  25. package/src/core/project.mjs +43 -8
  26. package/src/core/react-run.mjs +96 -0
  27. package/src/core/runtime-go/thunder_runtime.go +3038 -0
  28. package/src/core/runtime-react.mjs +133 -0
  29. package/src/core/runtime-typescript.mjs +119 -0
  30. package/src/core/rust/thunder_runtime.rs +1645 -0
  31. package/src/core/rust-run.mjs +192 -0
  32. package/src/core/screen-values.mjs +30 -0
  33. package/src/core/target-csharp.mjs +484 -0
  34. package/src/core/target-go.mjs +555 -0
  35. package/src/core/target-java.mjs +587 -0
  36. package/src/core/target-python.mjs +2 -1
  37. package/src/core/target-react.mjs +270 -0
  38. package/src/core/target-rust.mjs +534 -0
  39. package/src/core/target-typescript.mjs +466 -0
  40. package/src/core/typescript-run.mjs +114 -0
  41. package/src/core.d.ts +18 -0
  42. package/src/core.mjs +1 -0
  43. package/src/emit.mjs +1 -1
  44. package/src/faithful.mjs +30 -0
  45. package/src/learn-lessons.mjs +245 -1
  46. package/src/learn.d.mts +8 -0
  47. package/src/learn.mjs +40 -4
  48. package/src/libraries.mjs +10 -3
  49. package/src/model.mjs +50 -8
  50. package/src/read-level.mjs +192 -0
  51. package/src/read-repo-fs.mjs +3 -1
  52. package/src/read.mjs +28 -5
  53. package/src/replay-cli.mjs +123 -0
  54. package/src/say-less.mjs +152 -11
  55. package/src/screens.mjs +833 -0
  56. package/src/steps.mjs +430 -19
  57. package/src/term.mjs +132 -0
  58. package/src/try-cli.mjs +225 -0
  59. package/src/why-cli.mjs +17 -7
  60. package/src/why.d.mts +17 -7
  61. package/src/why.mjs +114 -33
@@ -0,0 +1,1374 @@
1
+ // ThunderRuntime.java: written by the Thunder compiler next to compiled Java. Standard library only (JDK 17+).
2
+ // The values and rules here are the Thunder engine's own (engine-values.mjs), line for line, so compiled Java, the
3
+ // Thunder engine, compiled TypeScript, and compiled Python say the same thing for the same program.
4
+ //
5
+ // Values: whole number -> BigInteger decimal number -> Dec (exact, like Python's Decimal)
6
+ // money -> Money text -> String yes/no -> Boolean nothing -> null
7
+ // list -> ArrayList (a pair from a map is a Tuple) map -> PyDict
8
+ // record -> RecordVal date -> PyDate
9
+ package thunder;
10
+
11
+ import java.io.ByteArrayOutputStream;
12
+ import java.io.FileDescriptor;
13
+ import java.io.FileOutputStream;
14
+ import java.io.IOException;
15
+ import java.io.PrintStream;
16
+ import java.math.BigInteger;
17
+ import java.nio.charset.StandardCharsets;
18
+ import java.nio.file.Files;
19
+ import java.nio.file.NoSuchFileException;
20
+ import java.nio.file.Path;
21
+ import java.nio.file.Paths;
22
+ import java.time.LocalDate;
23
+ import java.util.ArrayList;
24
+ import java.util.Arrays;
25
+ import java.util.Collections;
26
+ import java.util.HashMap;
27
+ import java.util.HashSet;
28
+ import java.util.Iterator;
29
+ import java.util.LinkedHashMap;
30
+ import java.util.List;
31
+ import java.util.Map;
32
+ import java.util.NoSuchElementException;
33
+ import java.util.Set;
34
+ import java.util.function.Function;
35
+ import java.util.function.Predicate;
36
+ import java.util.function.Supplier;
37
+ import java.util.regex.Matcher;
38
+ import java.util.regex.Pattern;
39
+
40
+ public class ThunderRuntime {
41
+ protected ThunderRuntime() {}
42
+
43
+ // ── Errors ─────────────────────────────────────────────────────────────────────────────────────────────────────
44
+
45
+ /** Where an error happened: a file and a Thunder line. */
46
+ public static final class Where {
47
+ public final String file; public final int line;
48
+ public Where(String file, int line) { this.file = file; this.line = line; }
49
+ }
50
+
51
+ /**
52
+ * A Thunder error (thunder = true: code TC5xx, message in words) or an error Python itself raises (TypeError,
53
+ * KeyError, ...), with Python's own message.
54
+ */
55
+ public static final class TErr extends RuntimeException {
56
+ public final String pyType; public final String code; public final boolean thunder; public final List<Object> args;
57
+ public List<Where> where;
58
+ TErr(String code, String message, String pyType, boolean thunder, List<Object> args) {
59
+ super(message, null, false, false);
60
+ this.code = code; this.pyType = pyType; this.thunder = thunder; this.args = args;
61
+ }
62
+ }
63
+ static TErr thunderErr(String code, String m, String pyType) { return new TErr(code, m, pyType, true, null); }
64
+ public static TErr Stop(Object m) { return thunderErr("TC507", (String) m, "Stop"); }
65
+ static TErr RuleBroken(String m) { return thunderErr("TC504", m, "RuleBroken"); }
66
+ static TErr ExpectationFailed(String m) { return thunderErr("TC505", m, "ExpectationFailed"); }
67
+ static TErr KindMismatch(String m) { return thunderErr("TC506", m, "TypeError"); }
68
+ static TErr ConversionFailed(String m) { return thunderErr("TC509", m, "ValueError"); }
69
+ static TErr MissingValue(String m) { return thunderErr("TC503", m, "LookupError"); }
70
+ static TErr DividedByZero(String m) { return thunderErr("TC501", m, "ZeroDivisionError"); }
71
+ static TErr PyErr(String pyType, String m) { return new TErr(null, m, pyType, false, Collections.singletonList(m)); }
72
+ static TErr PyErr(String pyType, String m, List<Object> args) { return new TErr(null, m, pyType, false, args); }
73
+ static TErr TypeErr(String m) { return PyErr("TypeError", m); }
74
+
75
+ /** explain(error) in thunder_runtime.py: the error as a sentence. */
76
+ public static String explain(TErr e) {
77
+ if (e.thunder) return e.getMessage();
78
+ String t = e.pyType, m = e.getMessage();
79
+ if (t.equals("ZeroDivisionError") || t.equals("DivisionByZero")) return "You divided by zero.";
80
+ if (t.equals("InvalidOperation")) return "This calculation has no answer (for example, zero divided by zero).";
81
+ if (t.equals("KeyError")) return "There is no entry for " + show(e.args.isEmpty() ? null : e.args.get(0)) + ".";
82
+ if ((t.equals("TypeError") || t.equals("AttributeError")) && m.contains("NoneType")) return "A value was nothing where a value was needed.";
83
+ if (t.equals("TypeError")) return "Values of different kinds were mixed (" + m + ").";
84
+ if (t.equals("RecursionError")) return "A function called itself too many times.";
85
+ return t + ": " + m;
86
+ }
87
+
88
+ /** _code(error) in thunder_runtime.py. */
89
+ static String codeOf(TErr e) {
90
+ if (e.thunder) return e.code;
91
+ String t = e.pyType, m = e.getMessage();
92
+ if (t.equals("ZeroDivisionError") || t.equals("DivisionByZero")) return "TC501";
93
+ if ((t.equals("TypeError") || t.equals("AttributeError")) && m.contains("NoneType")) return "TC502";
94
+ if (t.equals("KeyError")) return "TC503";
95
+ if (t.equals("TypeError")) return "TC506";
96
+ return "TC508";
97
+ }
98
+
99
+ /** A Java error that is not a Thunder or Python error is a bug in the runtime: it is not hidden. */
100
+ public static TErr asPyErr(Throwable e) {
101
+ if (e instanceof TErr) return (TErr) e;
102
+ if (e instanceof StackOverflowError) return PyErr("RecursionError", "maximum recursion depth exceeded");
103
+ if (e instanceof RuntimeException) throw (RuntimeException) e;
104
+ if (e instanceof Error) throw (Error) e;
105
+ throw new RuntimeException(e);
106
+ }
107
+
108
+ // ── Exact decimals: Python's Decimal with its default context (28 digits, half-even when a result is too long) ──
109
+
110
+ static final int PREC = 28;
111
+ static final BigInteger TEN = BigInteger.TEN, TWO = BigInteger.TWO, FIVE = BigInteger.valueOf(5);
112
+ static BigInteger pow10(int n) { return TEN.pow(n); }
113
+ static int ndigits(BigInteger c) { return c.signum() == 0 ? 1 : c.toString().length(); }
114
+ static boolean odd(BigInteger q) { return q.testBit(0); }
115
+
116
+ public static final class Dec {
117
+ final int s; final BigInteger c; final int e; // sign (0 or 1), coefficient >= 0, exponent
118
+ Dec(int s, BigInteger c, int e) { this.s = s; this.c = c; this.e = e; }
119
+ static Dec of(Object x) {
120
+ if (x instanceof Dec) return (Dec) x;
121
+ if (x instanceof BigInteger) return Dec.integer((BigInteger) x);
122
+ if (x instanceof Boolean) return Dec.integer((Boolean) x ? BigInteger.ONE : BigInteger.ZERO);
123
+ throw new ClassCastException("not a number");
124
+ }
125
+ static Dec integer(BigInteger n) { return new Dec(n.signum() < 0 ? 1 : 0, n.abs(), 0); }
126
+ static final Pattern NUM = Pattern.compile("^([+-]?)(\\d*)(?:\\.(\\d*))?(?:[eE]([+-]?\\d+))?$");
127
+ /** Decimal("text"): exact. Returns null when the text is not a number. */
128
+ static Dec parse(String text) {
129
+ Matcher m = NUM.matcher(text.strip().replace("_", ""));
130
+ if (!m.matches()) return null;
131
+ String ip = m.group(2), fp = m.group(3);
132
+ if ((ip == null || ip.isEmpty()) && fp == null) return null;
133
+ String frac = fp == null ? "" : fp;
134
+ String digits = (ip == null ? "" : ip) + frac;
135
+ return new Dec("-".equals(m.group(1)) ? 1 : 0, new BigInteger(digits.isEmpty() ? "0" : digits), (m.group(4) != null ? Integer.parseInt(m.group(4)) : 0) - frac.length());
136
+ }
137
+ boolean isZero() { return c.signum() == 0; }
138
+ /** _fix: round to 28 significant digits, half to even. */
139
+ Dec fix() {
140
+ int d = ndigits(c) - PREC;
141
+ if (d <= 0) return this;
142
+ BigInteger p = pow10(d);
143
+ BigInteger[] qr = c.divideAndRemainder(p);
144
+ BigInteger q = qr[0], r = qr[1], half = FIVE.multiply(pow10(d - 1));
145
+ int cmp = r.compareTo(half);
146
+ if (cmp > 0 || (cmp == 0 && odd(q))) q = q.add(BigInteger.ONE);
147
+ int ee = e + d;
148
+ if (ndigits(q) > PREC) { q = q.divide(TEN); ee += 1; }
149
+ return new Dec(s, q, ee);
150
+ }
151
+ BigInteger signed() { return s == 1 ? c.negate() : c; }
152
+ static Dec add(Dec a, Dec b) {
153
+ int e = Math.min(a.e, b.e);
154
+ BigInteger x = a.signed().multiply(pow10(a.e - e)), y = b.signed().multiply(pow10(b.e - e));
155
+ BigInteger sum = x.add(y);
156
+ int s;
157
+ if (sum.signum() == 0) s = a.s == 1 && b.s == 1 && a.c.signum() == 0 && b.c.signum() == 0 ? 1 : (a.c.signum() == 0 && b.c.signum() == 0 ? Math.min(a.s, b.s) : 0);
158
+ else s = sum.signum() < 0 ? 1 : 0;
159
+ return new Dec(s, sum.abs(), e).fix();
160
+ }
161
+ Dec negated() { return new Dec(s == 1 ? 0 : 1, c, e); }
162
+ static Dec sub(Dec a, Dec b) { return Dec.add(a, b.negated()); }
163
+ static Dec mul(Dec a, Dec b) { return new Dec(a.s ^ b.s, a.c.multiply(b.c), a.e + b.e).fix(); }
164
+ /** Python's Decimal division: exact when it can be, else 28 digits. */
165
+ static Dec div(Dec a, Dec b) {
166
+ int s = a.s ^ b.s;
167
+ if (a.c.signum() == 0) return new Dec(s, BigInteger.ZERO, a.e - b.e).fix();
168
+ int shift = ndigits(b.c) - ndigits(a.c) + PREC + 1;
169
+ int exp = a.e - b.e - shift;
170
+ BigInteger coeff, rem;
171
+ if (shift >= 0) { BigInteger[] qr = a.c.multiply(pow10(shift)).divideAndRemainder(b.c); coeff = qr[0]; rem = qr[1]; }
172
+ else { BigInteger[] qr = a.c.divideAndRemainder(b.c.multiply(pow10(-shift))); coeff = qr[0]; rem = qr[1]; }
173
+ if (rem.signum() != 0) { if (coeff.mod(FIVE).signum() == 0) coeff = coeff.add(BigInteger.ONE); }
174
+ else { int ideal = a.e - b.e; while (exp < ideal && coeff.mod(TEN).signum() == 0) { coeff = coeff.divide(TEN); exp += 1; } }
175
+ return new Dec(s, coeff, exp).fix();
176
+ }
177
+ /** Decimal % Decimal: the remainder with the sign of the dividend. */
178
+ static Dec rem(Dec a, Dec b) {
179
+ int e = Math.min(a.e, b.e);
180
+ BigInteger x = a.c.multiply(pow10(a.e - e)), y = b.c.multiply(pow10(b.e - e));
181
+ return new Dec(a.s, x.mod(y), e).fix();
182
+ }
183
+ Dec neg() { return (c.signum() == 0 ? new Dec(0, BigInteger.ZERO, e) : negated()).fix(); }
184
+ Dec abs() { return new Dec(0, c, e).fix(); }
185
+ static int cmp(Dec a, Dec b) {
186
+ int e = Math.min(a.e, b.e);
187
+ BigInteger x = a.signed().multiply(pow10(a.e - e)), y = b.signed().multiply(pow10(b.e - e));
188
+ return Integer.signum(x.compareTo(y));
189
+ }
190
+ /** quantize to exponent `e` rounding half away from zero. */
191
+ Dec quantizeHalfUp(int ne) {
192
+ if (ne <= e) return new Dec(s, c.multiply(pow10(e - ne)), ne);
193
+ BigInteger p = pow10(ne - e);
194
+ BigInteger[] qr = c.divideAndRemainder(p);
195
+ BigInteger q = qr[0];
196
+ if (qr[1].multiply(TWO).compareTo(p) >= 0) q = q.add(BigInteger.ONE);
197
+ return new Dec(s, q, ne);
198
+ }
199
+ boolean isIntegral() { if (e >= 0) return true; return c.mod(pow10(-e)).signum() == 0; }
200
+ /** int(d): toward zero. */
201
+ BigInteger toBigInt() { BigInteger v = e >= 0 ? c.multiply(pow10(e)) : c.divide(pow10(-e)); return s == 1 ? v.negate() : v; }
202
+ /** str(Decimal): Python's to-scientific-string. */
203
+ @Override public String toString() {
204
+ String digits = c.toString();
205
+ int left = e + digits.length();
206
+ int dot = e <= 0 && left > -6 ? left : 1;
207
+ String ip, fp;
208
+ if (dot <= 0) { ip = "0"; fp = "." + "0".repeat(-dot) + digits; }
209
+ else if (dot >= digits.length()) { ip = digits + "0".repeat(dot - digits.length()); fp = ""; }
210
+ else { ip = digits.substring(0, dot); fp = "." + digits.substring(dot); }
211
+ String ex = left == dot ? "" : "E" + (left - dot >= 0 ? "+" : "") + (left - dot);
212
+ return (s == 1 ? "-" : "") + ip + fp + ex;
213
+ }
214
+ String toFixed() { return toFixed(null, false); }
215
+ /** format(d, "f") or format(d, ",.Nf"). */
216
+ String toFixed(Integer places, boolean group) {
217
+ Dec d = this;
218
+ if (places != null) d = d.roundHalfEven(-places);
219
+ String digits = d.c.toString();
220
+ int dot = d.e + digits.length();
221
+ String ip, fp;
222
+ if (dot < 0) { ip = "0"; fp = "0".repeat(-dot) + digits; }
223
+ else if (dot > digits.length()) { ip = digits + "0".repeat(dot - digits.length()); fp = ""; }
224
+ else { ip = digits.substring(0, dot); if (ip.isEmpty()) ip = "0"; fp = digits.substring(dot); }
225
+ if (group) ip = groupThousands(ip);
226
+ return (d.s == 1 ? "-" : "") + ip + (fp.isEmpty() ? "" : "." + fp);
227
+ }
228
+ Dec roundHalfEven(int ne) {
229
+ if (ne <= e) return new Dec(s, c.multiply(pow10(e - ne)), ne);
230
+ BigInteger p = pow10(ne - e);
231
+ BigInteger[] qr = c.divideAndRemainder(p);
232
+ BigInteger q = qr[0];
233
+ int cmp = qr[1].multiply(TWO).compareTo(p);
234
+ if (cmp > 0 || (cmp == 0 && odd(q))) q = q.add(BigInteger.ONE);
235
+ return new Dec(s, q, ne);
236
+ }
237
+ /** A key equal for equal numbers (1 and 1.0 and 1.00 are the same map key, as in Python). */
238
+ String key() {
239
+ if (c.signum() == 0) return "0";
240
+ BigInteger cc = c; int ee = e;
241
+ while (cc.mod(TEN).signum() == 0) { cc = cc.divide(TEN); ee += 1; }
242
+ return (s == 1 ? "-" : "") + cc + "e" + ee;
243
+ }
244
+ }
245
+
246
+ static String groupThousands(String ip) {
247
+ StringBuilder b = new StringBuilder();
248
+ int n = ip.length();
249
+ for (int i = 0; i < n; i++) { if (i > 0 && (n - i) % 3 == 0) b.append(','); b.append(ip.charAt(i)); }
250
+ return b.toString();
251
+ }
252
+
253
+ // ── Money ──────────────────────────────────────────────────────────────────────────────────────────────────────
254
+
255
+ public static final class Money {
256
+ final Dec amount;
257
+ Money(Dec amount) { this.amount = amount; }
258
+ static Money of(Object x) {
259
+ if (x instanceof Money) return (Money) x;
260
+ if (x instanceof String) {
261
+ Dec d = Dec.parse(((String) x).replace(",", "").replace("$", "").strip());
262
+ if (d == null) throw PyErr("InvalidOperation", "[<class 'decimal.ConversionSyntax'>]");
263
+ return new Money(d);
264
+ }
265
+ return new Money(toDec(x));
266
+ }
267
+ @Override public String toString() {
268
+ Dec a = amount;
269
+ int places = a.e < 0 ? Math.max(2, -a.e) : 2;
270
+ return (a.s == 1 && a.c.signum() != 0 ? "-$" : "$") + a.abs().toFixed(places, true);
271
+ }
272
+ }
273
+
274
+ /** Money._other: the amount of the other side, or a clear error. */
275
+ static Dec moneyOther(Object other, String verb) {
276
+ if (other instanceof Money) return ((Money) other).amount;
277
+ if (isNumber(other) && numCmp(other, BigInteger.ZERO) == 0) return Dec.integer(BigInteger.ZERO);
278
+ throw KindMismatch("I can't " + verb + " money and " + describe(other) + ". Write the number as money, for example $5.");
279
+ }
280
+
281
+ // ── Other kinds ────────────────────────────────────────────────────────────────────────────────────────────────
282
+
283
+ public static final class PyDate {
284
+ final int y, m, d;
285
+ PyDate(int y, int m, int d) { this.y = y; this.m = m; this.d = d; }
286
+ String iso() { return String.format("%04d-%02d-%02d", y, m, d); }
287
+ int num() { return y * 10000 + m * 100 + d; }
288
+ static PyDate todayDate() { LocalDate t = LocalDate.now(); return new PyDate(t.getYear(), t.getMonthValue(), t.getDayOfMonth()); }
289
+ static final Pattern ISO = Pattern.compile("^(\\d{4})-?(\\d{2})-?(\\d{2})$");
290
+ /** date.fromisoformat for YYYY-MM-DD (and YYYYMMDD); null when it is not a date. */
291
+ static PyDate parse(String text) {
292
+ Matcher mm = ISO.matcher(text);
293
+ if (!mm.matches()) return null;
294
+ int y = Integer.parseInt(mm.group(1)), mo = Integer.parseInt(mm.group(2)), d = Integer.parseInt(mm.group(3));
295
+ int[] days = { 31, (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
296
+ if (y < 1 || mo < 1 || mo > 12 || d < 1 || d > days[mo - 1]) return null;
297
+ return new PyDate(y, mo, d);
298
+ }
299
+ }
300
+
301
+ public static final class Tuple { final List<Object> items; Tuple(List<Object> items) { this.items = items; } }
302
+
303
+ public static final class NotGiven { private NotGiven() {} }
304
+ public static final Object NOT_GIVEN = new NotGiven();
305
+
306
+ /** A Python dict: insertion order kept; keys equal the way Python compares them (1 == 1.0 == True). */
307
+ public static final class PyDict {
308
+ final LinkedHashMap<String, Object[]> m = new LinkedHashMap<>();
309
+ static String keyOf(Object k) {
310
+ if (k == null) return "N";
311
+ if (k instanceof String) return "s" + k;
312
+ if (k instanceof Boolean || k instanceof BigInteger || k instanceof Dec) return "n" + Dec.of(k).key();
313
+ if (k instanceof Money) return "m" + ((Money) k).amount.key();
314
+ if (k instanceof PyDate) return "d" + ((PyDate) k).iso();
315
+ if (k instanceof Tuple) { StringBuilder b = new StringBuilder("t("); List<Object> it = ((Tuple) k).items; for (int i = 0; i < it.size(); i++) { if (i > 0) b.append(','); b.append(keyOf(it.get(i))); } return b.append(')').toString(); }
316
+ if (k == NOT_GIVEN) return "G";
317
+ throw TypeErr("unhashable type: '" + typeName(k) + "'");
318
+ }
319
+ boolean has(Object k) { return m.containsKey(keyOf(k)); }
320
+ Object get(Object k) { Object[] e = m.get(keyOf(k)); return e == null ? null : e[1]; }
321
+ void set(Object k, Object v) { String id = keyOf(k); Object[] e = m.get(id); if (e != null) e[1] = v; else m.put(id, new Object[] { k, v }); }
322
+ void delete(Object k) { m.remove(keyOf(k)); }
323
+ int size() { return m.size(); }
324
+ ArrayList<Object> keys() { ArrayList<Object> out = new ArrayList<>(); for (Object[] e : m.values()) out.add(e[0]); return out; }
325
+ ArrayList<Object> values() { ArrayList<Object> out = new ArrayList<>(); for (Object[] e : m.values()) out.add(e[1]); return out; }
326
+ ArrayList<Object> items() { ArrayList<Object> out = new ArrayList<>(); for (Object[] e : m.values()) out.add(new Tuple(new ArrayList<>(Arrays.asList(e[0], e[1])))); return out; }
327
+ }
328
+
329
+ /** A field of a record kind: its Python name and its kind. */
330
+ public static final class Field { final String py; final String kind; public Field(String py, String kind) { this.py = py; this.kind = kind; } }
331
+ /** A Never rule on a record's field: the condition that breaks it (run with the new value), its words and line. */
332
+ public static final class Rule {
333
+ final Function<Object, Object> cond; final String text; final int line;
334
+ public Rule(Function<Object, Object> cond, String text, int line) { this.cond = cond; this.text = text; this.line = line; }
335
+ }
336
+ /** A record kind (a Python dataclass): its name, fields, and the Never rules on its fields. */
337
+ public static final class RecordKind {
338
+ final String py; final List<Field> fields; final Map<String, List<Rule>> rules;
339
+ RecordKind(String py, List<Field> fields, Map<String, List<Rule>> rules) { this.py = py; this.fields = fields; this.rules = rules; }
340
+ }
341
+ /** A record: its kind, and its field values in declaration order. */
342
+ public static final class RecordVal {
343
+ final RecordKind cls; final LinkedHashMap<String, Object> f = new LinkedHashMap<>();
344
+ RecordVal(RecordKind cls) { this.cls = cls; }
345
+ }
346
+
347
+ /** A name a lambda in the generated code also uses (Java lambdas only see names that never change). */
348
+ public static final class Box { public Object v; public Box(Object v) { this.v = v; } }
349
+
350
+ // ── Kinds ──────────────────────────────────────────────────────────────────────────────────────────────────────
351
+
352
+ static boolean isInt(Object x) { return x instanceof BigInteger; }
353
+ static boolean isNumber(Object x) { return x instanceof BigInteger || x instanceof Dec; } // _is_number: never yes/no
354
+ static boolean isIntLike(Object x) { return x instanceof BigInteger || x instanceof Boolean; }
355
+ static boolean isNumLike(Object x) { return isIntLike(x) || x instanceof Dec; } // what Python arithmetic accepts as a number
356
+ static BigInteger asBig(Object x) { return x instanceof Boolean ? ((Boolean) x ? BigInteger.ONE : BigInteger.ZERO) : (BigInteger) x; }
357
+ static int numCmp(Object a, Object b) { return isIntLike(a) && isIntLike(b) ? Integer.signum(asBig(a).compareTo(asBig(b))) : Dec.cmp(Dec.of(a), Dec.of(b)); }
358
+ static boolean isList(Object x) { return x instanceof ArrayList; }
359
+ @SuppressWarnings("unchecked") static ArrayList<Object> asList(Object x) { return (ArrayList<Object>) x; }
360
+
361
+ /** Python's type name, as its error messages print it. */
362
+ static String typeName(Object v) {
363
+ if (v == null) return "NoneType";
364
+ if (v instanceof Boolean) return "bool";
365
+ if (v instanceof BigInteger) return "int";
366
+ if (v instanceof String) return "str";
367
+ if (v instanceof Dec) return "decimal.Decimal";
368
+ if (v instanceof Money) return "Money";
369
+ if (isList(v)) return "list";
370
+ if (v instanceof Tuple) return "tuple";
371
+ if (v instanceof PyDict) return "dict";
372
+ if (v instanceof PyDate) return "datetime.date";
373
+ if (v instanceof RecordVal) return ((RecordVal) v).cls.py;
374
+ if (v == NOT_GIVEN) return "_NotGiven";
375
+ return "object";
376
+ }
377
+ static String shortName(Object v) { return v instanceof Dec ? "Decimal" : v instanceof PyDate ? "date" : typeName(v); }
378
+
379
+ /** _describe(v) in thunder_runtime.py. */
380
+ static String describe(Object v) {
381
+ if (v == null) return "nothing";
382
+ if (v instanceof Boolean) return "a yes/no value";
383
+ if (v instanceof String) return "the text \"" + v + "\"";
384
+ if (isNumber(v)) return "the number " + show(v);
385
+ if (v instanceof Money) return v.toString();
386
+ return "a value (" + shortName(v) + ")";
387
+ }
388
+
389
+ /** show(v): a value the way Thunder says it. */
390
+ public static String show(Object v) {
391
+ if (v == null) return "nothing";
392
+ if (Boolean.TRUE.equals(v)) return "yes";
393
+ if (Boolean.FALSE.equals(v)) return "no";
394
+ if (v instanceof Dec) { String t = ((Dec) v).toFixed(); return t.contains(".") ? t.replaceAll("0+$", "").replaceAll("\\.$", "") : t; }
395
+ if (isList(v)) return "[" + joinShow(asList(v)) + "]";
396
+ if (v instanceof Tuple) return "[" + joinShow(((Tuple) v).items) + "]";
397
+ if (v instanceof PyDict) { StringBuilder b = new StringBuilder("{"); boolean first = true; for (Object[] e : ((PyDict) v).m.values()) { if (!first) b.append(", "); first = false; b.append(show(e[0])).append(": ").append(show(e[1])); } return b.append('}').toString(); }
398
+ if (v instanceof RecordVal) {
399
+ RecordVal r = (RecordVal) v;
400
+ StringBuilder b = new StringBuilder(r.cls.py).append('(');
401
+ for (int i = 0; i < r.cls.fields.size(); i++) { Field f = r.cls.fields.get(i); if (i > 0) b.append(", "); b.append(f.py.replace('_', ' ')).append(": ").append(show(r.f.get(f.py))); }
402
+ return b.append(')').toString();
403
+ }
404
+ if (v instanceof PyDate) return ((PyDate) v).iso();
405
+ return pyStr(v);
406
+ }
407
+ static String joinShow(List<Object> xs) { StringBuilder b = new StringBuilder(); for (int i = 0; i < xs.size(); i++) { if (i > 0) b.append(", "); b.append(show(xs.get(i))); } return b.toString(); }
408
+
409
+ /** Python's repr(v). */
410
+ static String pyRepr(Object v) {
411
+ if (v instanceof String) {
412
+ String s = (String) v;
413
+ char q = s.indexOf('\'') >= 0 && s.indexOf('"') < 0 ? '"' : '\'';
414
+ StringBuilder out = new StringBuilder();
415
+ s.codePoints().forEach((cp) -> {
416
+ if (cp == '\\') out.append("\\\\");
417
+ else if (cp == q) out.append('\\').append(q);
418
+ else if (cp == '\n') out.append("\\n");
419
+ else if (cp == '\r') out.append("\\r");
420
+ else if (cp == '\t') out.append("\\t");
421
+ else if (cp < 0x20 || cp == 0x7f) out.append(String.format("\\x%02x", cp));
422
+ else out.appendCodePoint(cp);
423
+ });
424
+ return q + out.toString() + q;
425
+ }
426
+ if (v == null) return "None";
427
+ if (v instanceof Boolean) return (Boolean) v ? "True" : "False";
428
+ if (v instanceof BigInteger) return v.toString();
429
+ if (v instanceof Dec) return "Decimal('" + v + "')";
430
+ if (v instanceof Money) return "Money('" + ((Money) v).amount.toFixed() + "')";
431
+ if (isList(v)) { StringBuilder b = new StringBuilder("["); List<Object> xs = asList(v); for (int i = 0; i < xs.size(); i++) { if (i > 0) b.append(", "); b.append(pyRepr(xs.get(i))); } return b.append(']').toString(); }
432
+ if (v instanceof Tuple) {
433
+ List<Object> xs = ((Tuple) v).items;
434
+ if (xs.size() == 1) return "(" + pyRepr(xs.get(0)) + ",)";
435
+ StringBuilder b = new StringBuilder("("); for (int i = 0; i < xs.size(); i++) { if (i > 0) b.append(", "); b.append(pyRepr(xs.get(i))); } return b.append(')').toString();
436
+ }
437
+ if (v instanceof PyDict) { StringBuilder b = new StringBuilder("{"); boolean first = true; for (Object[] e : ((PyDict) v).m.values()) { if (!first) b.append(", "); first = false; b.append(pyRepr(e[0])).append(": ").append(pyRepr(e[1])); } return b.append('}').toString(); }
438
+ if (v instanceof PyDate) { PyDate d = (PyDate) v; return "datetime.date(" + d.y + ", " + d.m + ", " + d.d + ")"; }
439
+ if (v instanceof RecordVal) {
440
+ RecordVal r = (RecordVal) v;
441
+ StringBuilder b = new StringBuilder(r.cls.py).append('(');
442
+ for (int i = 0; i < r.cls.fields.size(); i++) { Field f = r.cls.fields.get(i); if (i > 0) b.append(", "); b.append(f.py).append('=').append(pyRepr(r.f.get(f.py))); }
443
+ return b.append(')').toString();
444
+ }
445
+ if (v == NOT_GIVEN) return "not given";
446
+ return String.valueOf(v);
447
+ }
448
+
449
+ /** Python's str(v). */
450
+ public static String pyStr(Object v) {
451
+ if (v instanceof String) return (String) v;
452
+ if (v instanceof Money) return v.toString();
453
+ if (v instanceof PyDate) return ((PyDate) v).iso();
454
+ if (v instanceof Dec) return v.toString();
455
+ return pyRepr(v);
456
+ }
457
+
458
+ /** Python's truth value (used only where the generated Python uses it: "where" conditions and Never rules). */
459
+ public static boolean truthy(Object v) {
460
+ if (v == null || Boolean.FALSE.equals(v)) return false;
461
+ if (Boolean.TRUE.equals(v)) return true;
462
+ if (v instanceof BigInteger) return ((BigInteger) v).signum() != 0;
463
+ if (v instanceof Dec) return !((Dec) v).isZero();
464
+ if (v instanceof String) return !((String) v).isEmpty();
465
+ if (isList(v)) return !asList(v).isEmpty();
466
+ if (v instanceof Tuple) return !((Tuple) v).items.isEmpty();
467
+ if (v instanceof PyDict) return ((PyDict) v).size() > 0;
468
+ return true;
469
+ }
470
+
471
+ /** yes_no(v): a condition needs a real yes/no value. */
472
+ public static boolean yesNo(Object v) {
473
+ if (v instanceof Boolean) return (Boolean) v;
474
+ throw KindMismatch("This needs a yes/no value, but it is " + describe(v) + ". Compare it instead, for example: is 0, is empty, is nothing.");
475
+ }
476
+
477
+ /** _decimal(x) in thunder_runtime.py. */
478
+ static Dec toDec(Object x) {
479
+ if (x instanceof Dec) return (Dec) x;
480
+ if (x instanceof Boolean) throw KindMismatch("A yes/no value was used where a number was needed.");
481
+ if (x instanceof BigInteger) return Dec.integer((BigInteger) x);
482
+ if (x == null) throw KindMismatch("A value was nothing where a number was needed.");
483
+ throw KindMismatch(describe(x) + " was used where a number was needed.");
484
+ }
485
+
486
+ // ── Python operators ───────────────────────────────────────────────────────────────────────────────────────────
487
+
488
+ static int strLen(String s) { return s.codePointCount(0, s.length()); }
489
+ static ArrayList<Object> codePointList(String s) { ArrayList<Object> out = new ArrayList<>(); s.codePoints().forEach((cp) -> out.add(new String(Character.toChars(cp)))); return out; }
490
+
491
+ public static BigInteger pyLen(Object v) {
492
+ if (v instanceof String) return BigInteger.valueOf(strLen((String) v));
493
+ if (isList(v)) return BigInteger.valueOf(asList(v).size());
494
+ if (v instanceof Tuple) return BigInteger.valueOf(((Tuple) v).items.size());
495
+ if (v instanceof PyDict) return BigInteger.valueOf(((PyDict) v).size());
496
+ throw TypeErr("object of type '" + typeName(v) + "' has no len()");
497
+ }
498
+
499
+ /** Iterate a value the way Python's for loop does (a list is the list itself: items added while looping are seen). */
500
+ public static List<Object> pyIter(Object v) {
501
+ if (isList(v)) return asList(v);
502
+ if (v instanceof Tuple) return ((Tuple) v).items;
503
+ if (v instanceof String) return codePointList((String) v);
504
+ if (v instanceof PyDict) return ((PyDict) v).keys();
505
+ throw TypeErr("'" + typeName(v) + "' object is not iterable");
506
+ }
507
+ public static ArrayList<Object> pyList(Object v) { return new ArrayList<>(pyIter(v)); }
508
+
509
+ /** A for loop over a list, the way Python's goes: by position, so items added while looping are reached. */
510
+ public static Iterable<Object> loop(List<Object> items) {
511
+ return () -> new Iterator<Object>() {
512
+ int i = 0;
513
+ public boolean hasNext() { return i < items.size(); }
514
+ public Object next() { if (i >= items.size()) throw new NoSuchElementException(); return items.get(i++); }
515
+ };
516
+ }
517
+
518
+ public static Object add(Object a, Object b) {
519
+ if (a instanceof Money) return new Money(Dec.add(((Money) a).amount, moneyOther(b, "add")));
520
+ if (b instanceof Money) return new Money(Dec.add(((Money) b).amount, moneyOther(a, "add")));
521
+ if (isIntLike(a) && isIntLike(b)) return asBig(a).add(asBig(b));
522
+ if (isNumLike(a) && isNumLike(b)) return Dec.add(Dec.of(a), Dec.of(b));
523
+ if (a instanceof String) { if (b instanceof String) return (String) a + b; throw TypeErr("can only concatenate str (not \"" + typeName(b) + "\") to str"); }
524
+ if (isList(a)) { if (isList(b)) { ArrayList<Object> out = new ArrayList<>(asList(a)); out.addAll(asList(b)); return out; } throw TypeErr("can only concatenate list (not \"" + typeName(b) + "\") to list"); }
525
+ if (a instanceof Tuple) { if (b instanceof Tuple) { ArrayList<Object> out = new ArrayList<>(((Tuple) a).items); out.addAll(((Tuple) b).items); return new Tuple(out); } throw TypeErr("can only concatenate tuple (not \"" + typeName(b) + "\") to tuple"); }
526
+ throw TypeErr("unsupported operand type(s) for +: '" + typeName(a) + "' and '" + typeName(b) + "'");
527
+ }
528
+
529
+ public static Object sub(Object a, Object b) {
530
+ if (a instanceof Money) return new Money(Dec.sub(((Money) a).amount, moneyOther(b, "subtract")));
531
+ if (b instanceof Money) return new Money(Dec.sub(moneyOther(a, "subtract"), ((Money) b).amount));
532
+ if (isIntLike(a) && isIntLike(b)) return asBig(a).subtract(asBig(b));
533
+ if (isNumLike(a) && isNumLike(b)) return Dec.sub(Dec.of(a), Dec.of(b));
534
+ throw TypeErr("unsupported operand type(s) for -: '" + typeName(a) + "' and '" + typeName(b) + "'");
535
+ }
536
+
537
+ static Object repeat(Object seq, Object n) {
538
+ long k = asBig(n).longValue();
539
+ if (seq instanceof String) return k > 0 ? ((String) seq).repeat((int) k) : "";
540
+ ArrayList<Object> out = new ArrayList<>();
541
+ for (long i = 0; i < k; i++) out.addAll(asList(seq));
542
+ return out;
543
+ }
544
+
545
+ public static Object mul(Object a, Object b) {
546
+ if (a instanceof Money) { if (b instanceof Money) throw KindMismatch("Money can't be multiplied by money."); return new Money(Dec.mul(((Money) a).amount, toDec(b))); }
547
+ if (b instanceof Money) return new Money(Dec.mul(((Money) b).amount, toDec(a)));
548
+ if (isIntLike(a) && isIntLike(b)) return asBig(a).multiply(asBig(b));
549
+ if (isNumLike(a) && isNumLike(b)) return Dec.mul(Dec.of(a), Dec.of(b));
550
+ boolean seqA = a instanceof String || isList(a), seqB = b instanceof String || isList(b);
551
+ if (seqA) { if (isIntLike(b)) return repeat(a, b); throw TypeErr("can't multiply sequence by non-int of type '" + typeName(b) + "'"); }
552
+ if (seqB) { if (isIntLike(a)) return repeat(b, a); throw TypeErr("can't multiply sequence by non-int of type '" + typeName(a) + "'"); }
553
+ throw TypeErr("unsupported operand type(s) for *: '" + typeName(a) + "' and '" + typeName(b) + "'");
554
+ }
555
+
556
+ public static Object neg(Object a) {
557
+ if (a instanceof Money) return new Money(((Money) a).amount.neg());
558
+ if (isIntLike(a)) return asBig(a).negate();
559
+ if (a instanceof Dec) return ((Dec) a).neg();
560
+ throw TypeErr("bad operand type for unary -: '" + typeName(a) + "'");
561
+ }
562
+
563
+ /** Python's % on two whole numbers: the sign of the divisor. */
564
+ public static Object intMod(Object a, Object b) {
565
+ if (!isIntLike(a) || !isIntLike(b)) return pyModGeneric(a, b);
566
+ BigInteger x = asBig(a), y = asBig(b);
567
+ if (y.signum() == 0) throw PyErr("ZeroDivisionError", "integer modulo by zero");
568
+ BigInteger r = x.remainder(y);
569
+ if (r.signum() != 0 && (r.signum() < 0) != (y.signum() < 0)) r = r.add(y);
570
+ return r;
571
+ }
572
+ static Object pyModGeneric(Object a, Object b) {
573
+ if (isNumLike(a) && isNumLike(b)) return modulo(a, b);
574
+ throw TypeErr("unsupported operand type(s) for %: '" + typeName(a) + "' and '" + typeName(b) + "'");
575
+ }
576
+
577
+ /** divide(a, b) in thunder_runtime.py: always exact. */
578
+ public static Object divide(Object a, Object b) {
579
+ if (a instanceof Money) {
580
+ if (b instanceof Money) { if (((Money) b).amount.isZero()) throw DividedByZero("You divided by zero."); return Dec.div(((Money) a).amount, ((Money) b).amount); }
581
+ Dec d = toDec(b);
582
+ if (d.isZero()) throw DividedByZero("You divided by zero.");
583
+ return new Money(Dec.div(((Money) a).amount, d));
584
+ }
585
+ if (b instanceof Money) throw KindMismatch("A plain number can't be divided by money.");
586
+ Dec x = toDec(a), y = toDec(b);
587
+ if (y.isZero()) throw DividedByZero("You divided by zero.");
588
+ return Dec.div(x, y);
589
+ }
590
+
591
+ /** modulo(a, b) in thunder_runtime.py. */
592
+ public static Object modulo(Object a, Object b) {
593
+ boolean money = a instanceof Money;
594
+ Dec x = money ? ((Money) a).amount : toDec(a);
595
+ Dec y = b instanceof Money ? ((Money) b).amount : toDec(b);
596
+ if (y.isZero()) throw DividedByZero("You divided by zero.");
597
+ Dec r = Dec.rem(x, y);
598
+ if (!r.isZero() && (r.s == 1) != (y.s == 1 && !y.isZero())) r = Dec.add(r, y);
599
+ if (money) return new Money(r);
600
+ return a instanceof BigInteger && b instanceof BigInteger ? r.toBigInt() : r;
601
+ }
602
+
603
+ /** round_to(x, places). */
604
+ public static Object roundTo(Object x) { return roundTo(x, BigInteger.ZERO); }
605
+ public static Object roundTo(Object x, Object places) {
606
+ int p = asBig(places instanceof Dec ? ((Dec) places).toBigInt() : places).intValue();
607
+ if (x instanceof Money) return new Money(((Money) x).amount.quantizeHalfUp(-p));
608
+ if (x instanceof BigInteger) return x;
609
+ Dec d = toDec(x).quantizeHalfUp(-p);
610
+ return p == 0 ? d.toBigInt() : d;
611
+ }
612
+
613
+ /** Python ==. */
614
+ public static boolean eq(Object a, Object b) {
615
+ if (a == b && !(a instanceof Dec)) return true;
616
+ if (a instanceof Money || b instanceof Money) {
617
+ Money m = a instanceof Money ? (Money) a : (Money) b;
618
+ Object o = a instanceof Money ? b : a;
619
+ if (o == null || o instanceof String || o instanceof Boolean) return false;
620
+ return Dec.cmp(m.amount, moneyOther(o, "compare")) == 0;
621
+ }
622
+ if (a == null || b == null) return false;
623
+ if (isNumLike(a) && isNumLike(b)) return numCmp(a, b) == 0;
624
+ if (a instanceof String || b instanceof String) return a.equals(b);
625
+ if (isList(a) && isList(b)) {
626
+ List<Object> x = asList(a), y = asList(b);
627
+ if (x.size() != y.size()) return false;
628
+ for (int i = 0; i < x.size(); i++) if (x.get(i) != y.get(i) && !eq(x.get(i), y.get(i))) return false;
629
+ return true;
630
+ }
631
+ if (a instanceof Tuple && b instanceof Tuple) {
632
+ List<Object> x = ((Tuple) a).items, y = ((Tuple) b).items;
633
+ if (x.size() != y.size()) return false;
634
+ for (int i = 0; i < x.size(); i++) if (!eq(x.get(i), y.get(i))) return false;
635
+ return true;
636
+ }
637
+ if (a instanceof PyDict && b instanceof PyDict) {
638
+ PyDict x = (PyDict) a, y = (PyDict) b;
639
+ if (x.size() != y.size()) return false;
640
+ for (Map.Entry<String, Object[]> e : x.m.entrySet()) { Object[] o = y.m.get(e.getKey()); if (o == null || !eq(e.getValue()[1], o[1])) return false; }
641
+ return true;
642
+ }
643
+ if (a instanceof RecordVal && b instanceof RecordVal) {
644
+ RecordVal x = (RecordVal) a, y = (RecordVal) b;
645
+ if (x.cls != y.cls) return false;
646
+ for (Field f : x.cls.fields) if (!eq(x.f.get(f.py), y.f.get(f.py))) return false;
647
+ return true;
648
+ }
649
+ if (a instanceof PyDate && b instanceof PyDate) return ((PyDate) a).num() == ((PyDate) b).num();
650
+ return false;
651
+ }
652
+
653
+ static String flip(String op) { switch (op) { case "<": return ">"; case ">": return "<"; case "<=": return ">="; case ">=": return "<="; default: return op; } }
654
+ static boolean holds(String op, int c) { return op.equals("<") ? c < 0 : op.equals(">") ? c > 0 : op.equals("<=") ? c <= 0 : c >= 0; }
655
+
656
+ /** Python <, >, <=, >= (and == / != through eq). */
657
+ public static boolean compare(String op, Object a, Object b) {
658
+ if (op.equals("==")) return eq(a, b);
659
+ if (op.equals("!=")) return !eq(a, b);
660
+ if (a instanceof Money || b instanceof Money) {
661
+ Money m = a instanceof Money ? (Money) a : (Money) b;
662
+ Object o = a instanceof Money ? b : a;
663
+ String o2 = a instanceof Money ? op : flip(op);
664
+ if (o == null) throw TypeErr("'" + o2 + "' not supported between instances of 'decimal.Decimal' and 'NoneType'");
665
+ return holds(o2, Dec.cmp(m.amount, moneyOther(o, "compare")));
666
+ }
667
+ Integer c = order(a, b);
668
+ if (c == null) throw TypeErr("'" + op + "' not supported between instances of '" + typeName(a) + "' and '" + typeName(b) + "'");
669
+ return holds(op, c);
670
+ }
671
+
672
+ /** -1, 0, 1, or null when Python cannot order the two. */
673
+ static Integer order(Object a, Object b) {
674
+ if (isNumLike(a) && isNumLike(b)) return numCmp(a, b);
675
+ if (a instanceof String && b instanceof String) return cmpStr((String) a, (String) b);
676
+ if (a instanceof PyDate && b instanceof PyDate) return Integer.signum(((PyDate) a).num() - ((PyDate) b).num());
677
+ List<Object> seqA = isList(a) ? asList(a) : a instanceof Tuple ? ((Tuple) a).items : null;
678
+ List<Object> seqB = isList(b) ? asList(b) : b instanceof Tuple ? ((Tuple) b).items : null;
679
+ if (seqA != null && seqB != null && isList(a) == isList(b)) {
680
+ for (int i = 0; i < Math.min(seqA.size(), seqB.size()); i++) {
681
+ if (eq(seqA.get(i), seqB.get(i))) continue;
682
+ return compare("<", seqA.get(i), seqB.get(i)) ? -1 : 1;
683
+ }
684
+ return Integer.signum(seqA.size() - seqB.size());
685
+ }
686
+ return null;
687
+ }
688
+ static int cmpStr(String a, String b) {
689
+ int[] x = a.codePoints().toArray(), y = b.codePoints().toArray();
690
+ for (int i = 0; i < Math.min(x.length, y.length); i++) { int d = x[i] - y[i]; if (d != 0) return Integer.signum(d); }
691
+ return Integer.signum(x.length - y.length);
692
+ }
693
+
694
+ /** Python's `item in container`. */
695
+ static boolean contains(Object container, Object item) {
696
+ if (container instanceof String) {
697
+ if (!(item instanceof String)) throw TypeErr("'in <string>' requires string as left operand, not " + typeName(item));
698
+ return ((String) container).contains((String) item);
699
+ }
700
+ if (container instanceof PyDict) return ((PyDict) container).has(item);
701
+ if (isList(container)) { for (Object x : asList(container)) if (x == item || eq(x, item)) return true; return false; }
702
+ if (container instanceof Tuple) { for (Object x : ((Tuple) container).items) if (eq(x, item)) return true; return false; }
703
+ throw TypeErr("argument of type '" + typeName(container) + "' is not iterable");
704
+ }
705
+
706
+ /** Python's list.sort / sorted: stable, using < only. */
707
+ public static ArrayList<Object> pySort(List<Object> items, Function<Object, Object> key, boolean reverse) {
708
+ final class K { final Object v, k; final int i; K(Object v, Object k, int i) { this.v = v; this.k = k; this.i = i; } }
709
+ ArrayList<K> keyed = new ArrayList<>();
710
+ for (int i = 0; i < items.size(); i++) { Object v = items.get(i); keyed.add(new K(v, key != null ? key.apply(v) : v, i)); }
711
+ keyed.sort((x, y) -> {
712
+ if (compare("<", reverse ? y.k : x.k, reverse ? x.k : y.k)) return -1;
713
+ if (compare("<", reverse ? x.k : y.k, reverse ? y.k : x.k)) return 1;
714
+ return x.i - y.i;
715
+ });
716
+ ArrayList<Object> out = new ArrayList<>();
717
+ for (K k : keyed) out.add(k.v);
718
+ return out;
719
+ }
720
+
721
+ // ── Attribute-style Python calls the generated code makes on values ────────────────────────────────────────────
722
+
723
+ static TErr attrErr(Object v, String name) { return PyErr("AttributeError", "'" + typeName(v) + "' object has no attribute '" + name + "'"); }
724
+ static String strMethod(Object v, String name) { if (!(v instanceof String)) throw attrErr(v, name); return (String) v; }
725
+
726
+ static final Pattern SPLITLINES = Pattern.compile("\\r\\n|[\\n\\r\\u000b\\f\\u001c\\u001d\\u001e\\u0085\\u2028\\u2029]");
727
+ static ArrayList<Object> splitLines(String s) {
728
+ ArrayList<Object> out = new ArrayList<>();
729
+ String rest = s;
730
+ while (!rest.isEmpty()) {
731
+ Matcher m = SPLITLINES.matcher(rest);
732
+ if (!m.find()) { out.add(rest); break; }
733
+ out.add(rest.substring(0, m.start()));
734
+ rest = rest.substring(m.end());
735
+ }
736
+ return out;
737
+ }
738
+ // JavaScript's \s (with the u flag) plus Python's extra whitespace: \x1c-\x1f and \x85.
739
+ static final String WS = "\\t\\n\\u000b\\f\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff\\u001c-\\u001f\\u0085";
740
+ static final Pattern PY_SPACE = Pattern.compile("[" + WS + "]+");
741
+ static final Pattern PY_STRIP = Pattern.compile("^[" + WS + "]+|[" + WS + "]+$");
742
+ static ArrayList<Object> pySplit(String s) { ArrayList<Object> out = new ArrayList<>(); for (String p : PY_SPACE.split(s, -1)) if (!p.isEmpty()) out.add(p); return out; }
743
+ static String pyStrip(String s) { return PY_STRIP.matcher(s).replaceAll(""); }
744
+
745
+ // ── JSON, the way Python's json module reads and writes it ─────────────────────────────────────────────────────
746
+
747
+ static final class JsonError extends RuntimeException { final int pos; JsonError(String msg, int pos) { super(msg, null, false, false); this.pos = pos; } }
748
+
749
+ static final class Json {
750
+ final String s; final int n;
751
+ Json(String s) { this.s = s; this.n = s.length(); }
752
+ static final Pattern NUM = Pattern.compile("-?(?:0|[1-9]\\d*)(\\.\\d+)?([eE][-+]?\\d+)?");
753
+ int ws(int i) { while (i < n && " \t\n\r".indexOf(s.charAt(i)) >= 0) i++; return i; }
754
+ Object[] str(int begin) {
755
+ int i = begin + 1;
756
+ StringBuilder out = new StringBuilder();
757
+ for (;;) {
758
+ if (i >= n) throw new JsonError("Unterminated string starting at", begin);
759
+ char ch = s.charAt(i);
760
+ if (ch == '"') return new Object[] { out.toString(), i + 1 };
761
+ if (ch < 0x20) throw new JsonError("Invalid control character at", i);
762
+ if (ch != '\\') { out.append(ch); i++; continue; }
763
+ if (i + 1 >= n) throw new JsonError("Unterminated string starting at", begin);
764
+ char esc = s.charAt(i + 1);
765
+ String simple = esc == '"' ? "\"" : esc == '\\' ? "\\" : esc == '/' ? "/" : esc == 'b' ? "\b" : esc == 'f' ? "\f" : esc == 'n' ? "\n" : esc == 'r' ? "\r" : esc == 't' ? "\t" : null;
766
+ if (simple != null) { out.append(simple); i += 2; continue; }
767
+ if (esc != 'u') throw new JsonError("Invalid \\escape", i);
768
+ String hex = i + 6 <= n ? s.substring(i + 2, i + 6) : "";
769
+ if (!hex.matches("[0-9a-fA-F]{4}")) throw new JsonError("Invalid \\uXXXX escape", i + 1);
770
+ int cp = Integer.parseInt(hex, 16);
771
+ i += 6;
772
+ if (cp >= 0xd800 && cp <= 0xdbff && i + 6 <= n && s.charAt(i) == '\\' && s.charAt(i + 1) == 'u' && s.substring(i + 2, i + 6).matches("[0-9a-fA-F]{4}")) {
773
+ int lo = Integer.parseInt(s.substring(i + 2, i + 6), 16);
774
+ if (lo >= 0xdc00 && lo <= 0xdfff) { cp = 0x10000 + ((cp - 0xd800) << 10) + (lo - 0xdc00); i += 6; }
775
+ }
776
+ out.appendCodePoint(cp);
777
+ }
778
+ }
779
+ Object[] value(int i) {
780
+ if (i >= n) throw new JsonError("Expecting value", i);
781
+ char ch = s.charAt(i);
782
+ if (ch == '"') return str(i);
783
+ if (ch == '{') return obj(i + 1);
784
+ if (ch == '[') return arr(i + 1);
785
+ if (s.startsWith("null", i)) return new Object[] { null, i + 4 };
786
+ if (s.startsWith("true", i)) return new Object[] { true, i + 4 };
787
+ if (s.startsWith("false", i)) return new Object[] { false, i + 5 };
788
+ Matcher m = NUM.matcher(s);
789
+ m.region(i, n);
790
+ if (m.lookingAt()) {
791
+ String t = m.group();
792
+ if (m.group(1) != null || m.group(2) != null) return new Object[] { Dec.parse(t), i + t.length() };
793
+ return new Object[] { new BigInteger(t), i + t.length() };
794
+ }
795
+ throw new JsonError("Expecting value", i);
796
+ }
797
+ Object[] obj(int i) {
798
+ PyDict d = new PyDict();
799
+ i = ws(i);
800
+ if (i < n && s.charAt(i) == '}') return new Object[] { d, i + 1 };
801
+ for (;;) {
802
+ if (i >= n || s.charAt(i) != '"') throw new JsonError("Expecting property name enclosed in double quotes", i);
803
+ Object[] kr = str(i);
804
+ i = ws((Integer) kr[1]);
805
+ if (i >= n || s.charAt(i) != ':') throw new JsonError("Expecting ':' delimiter", i);
806
+ i = ws(i + 1);
807
+ Object[] vr = value(i);
808
+ i = (Integer) vr[1];
809
+ d.set(kr[0], vr[0]);
810
+ i = ws(i);
811
+ if (i < n && s.charAt(i) == '}') return new Object[] { d, i + 1 };
812
+ if (i >= n || s.charAt(i) != ',') throw new JsonError("Expecting ',' delimiter", i);
813
+ int comma = i;
814
+ i = ws(i + 1);
815
+ if (i < n && s.charAt(i) == '}') throw new JsonError("Illegal trailing comma before end of object", comma);
816
+ }
817
+ }
818
+ Object[] arr(int i) {
819
+ ArrayList<Object> out = new ArrayList<>();
820
+ i = ws(i);
821
+ if (i < n && s.charAt(i) == ']') return new Object[] { out, i + 1 };
822
+ for (;;) {
823
+ Object[] vr = value(i);
824
+ out.add(vr[0]);
825
+ i = ws((Integer) vr[1]);
826
+ if (i < n && s.charAt(i) == ']') return new Object[] { out, i + 1 };
827
+ if (i >= n || s.charAt(i) != ',') throw new JsonError("Expecting ',' delimiter", i);
828
+ int comma = i;
829
+ i = ws(i + 1);
830
+ if (i < n && s.charAt(i) == ']') throw new JsonError("Illegal trailing comma before end of array", comma);
831
+ }
832
+ }
833
+ }
834
+
835
+ static Object jsonParse(String text) {
836
+ Json j = new Json(text);
837
+ try {
838
+ Object[] r = j.value(j.ws(0));
839
+ int end = j.ws((Integer) r[1]);
840
+ if (end != j.n) throw new JsonError("Extra data", end);
841
+ return r[0];
842
+ } catch (JsonError e) {
843
+ String before = text.substring(0, e.pos);
844
+ int line = 1;
845
+ for (int i = 0; i < before.length(); i++) if (before.charAt(i) == '\n') line++;
846
+ int col = e.pos - before.lastIndexOf('\n');
847
+ throw ConversionFailed("This is not JSON: " + e.getMessage() + " (line " + line + ", column " + col + ").");
848
+ }
849
+ }
850
+
851
+ static Object jsonReady(Object v) {
852
+ if (v == null || v instanceof Boolean || v instanceof String || v instanceof BigInteger || v instanceof Dec) return v;
853
+ if (v instanceof Money) throw KindMismatch("Money has no JSON form of its own: use its amount, for example price's amount.");
854
+ if (isList(v)) { ArrayList<Object> out = new ArrayList<>(); for (Object x : asList(v)) out.add(jsonReady(x)); return out; }
855
+ if (v instanceof Tuple) { ArrayList<Object> out = new ArrayList<>(); for (Object x : ((Tuple) v).items) out.add(jsonReady(x)); return out; }
856
+ if (v instanceof PyDict) {
857
+ PyDict out = new PyDict();
858
+ for (Object[] e : ((PyDict) v).m.values()) { if (!(e[0] instanceof String)) throw KindMismatch("A JSON object's keys are text, but one is " + describe(e[0]) + "."); out.set(e[0], jsonReady(e[1])); }
859
+ return out;
860
+ }
861
+ if (v instanceof RecordVal) { RecordVal r = (RecordVal) v; PyDict out = new PyDict(); for (Field f : r.cls.fields) out.set(f.py, jsonReady(r.f.get(f.py))); return out; }
862
+ throw KindMismatch(describe(v) + " has no JSON form.");
863
+ }
864
+
865
+ static String jsonStr(String s) {
866
+ StringBuilder b = new StringBuilder("\"");
867
+ s.codePoints().forEach((cp) -> {
868
+ if (cp == '"') b.append("\\\"");
869
+ else if (cp == '\\') b.append("\\\\");
870
+ else if (cp == '\n') b.append("\\n");
871
+ else if (cp == '\r') b.append("\\r");
872
+ else if (cp == '\t') b.append("\\t");
873
+ else if (cp == '\b') b.append("\\b");
874
+ else if (cp == '\f') b.append("\\f");
875
+ else if (cp >= 0x20 && cp <= 0x7e) b.appendCodePoint(cp);
876
+ else if (cp > 0xffff) { int v = cp - 0x10000; b.append("\\u").append(Integer.toHexString(0xd800 + (v >> 10))).append("\\u").append(Integer.toHexString(0xdc00 + (v & 0x3ff))); }
877
+ else b.append(String.format("\\u%04x", cp));
878
+ });
879
+ return b.append('"').toString();
880
+ }
881
+
882
+ static String jsonText(Object v) { return jsonWrite(jsonReady(v)); }
883
+ static String jsonWrite(Object x) {
884
+ if (x == null) return "null";
885
+ if (Boolean.TRUE.equals(x)) return "true";
886
+ if (Boolean.FALSE.equals(x)) return "false";
887
+ if (x instanceof BigInteger) return x.toString();
888
+ if (x instanceof Dec) { Dec d = (Dec) x; String t = d.toString(); return d.isIntegral() && t.contains("E") ? d.toFixed() : t; }
889
+ if (x instanceof String) return jsonStr((String) x);
890
+ if (isList(x)) { StringBuilder b = new StringBuilder("["); List<Object> xs = asList(x); for (int i = 0; i < xs.size(); i++) { if (i > 0) b.append(", "); b.append(jsonWrite(xs.get(i))); } return b.append(']').toString(); }
891
+ StringBuilder b = new StringBuilder("{"); boolean first = true;
892
+ for (Object[] e : ((PyDict) x).m.values()) { if (!first) b.append(", "); first = false; b.append(jsonStr((String) e[0])).append(": ").append(jsonWrite(e[1])); }
893
+ return b.append('}').toString();
894
+ }
895
+
896
+ // ── Helpers the generated code calls ───────────────────────────────────────────────────────────────────────────
897
+
898
+ public static final int MAX_FRAMES = 997; // as deep as the generated Python goes (recursion limit 1000, less its own frames)
899
+
900
+ public static BigInteger rangeInt(Object v) {
901
+ if (v instanceof BigInteger) return (BigInteger) v;
902
+ if (v instanceof Boolean) return (Boolean) v ? BigInteger.ONE : BigInteger.ZERO;
903
+ throw TypeErr("'" + (v instanceof Dec ? "decimal.Decimal" : v == null ? "NoneType" : v instanceof Money ? "Money" : v instanceof String ? "str" : "object") + "' object cannot be interpreted as an integer");
904
+ }
905
+
906
+ public static List<Object> unpack2(Object el) {
907
+ List<Object> items = isList(el) ? asList(el) : el instanceof Tuple ? ((Tuple) el).items : el instanceof String ? codePointList((String) el) : el instanceof PyDict ? ((PyDict) el).keys() : null;
908
+ if (items == null) throw TypeErr("cannot unpack non-iterable " + (el == null ? "NoneType" : isInt(el) ? "int" : el instanceof Dec ? "decimal.Decimal" : el instanceof Boolean ? "bool" : "object") + " object");
909
+ if (items.size() < 2) throw PyErr("ValueError", "not enough values to unpack (expected 2, got " + items.size() + ")");
910
+ if (items.size() > 2) throw PyErr("ValueError", "too many values to unpack (expected 2, got " + items.size() + ")");
911
+ return items;
912
+ }
913
+
914
+ public static List<Object> mapItems(Object m) { if (!(m instanceof PyDict)) throw attrErr(m, "items"); return ((PyDict) m).items(); }
915
+ public static List<Object> pairsOf(Object c) { return c instanceof PyDict ? ((PyDict) c).items() : pyList(c); }
916
+
917
+ public static Object itemAt(Object items, Object position) { return itemAt(items, position, false, null); }
918
+ public static Object itemAt(Object items, Object position, Object dflt) { return itemAt(items, position, true, dflt); }
919
+ static Object itemAt(Object items, Object position, boolean hasDflt, Object dflt) {
920
+ if (!(position instanceof BigInteger)) throw KindMismatch("A position in a list is a whole number, not " + describe(position) + ".");
921
+ List<Object> list = isList(items) ? asList(items) : items instanceof Tuple ? ((Tuple) items).items : null;
922
+ if (list == null) throw TypeErr("object of type '" + (items == null ? "NoneType" : "object") + "' has no len()");
923
+ BigInteger p = (BigInteger) position;
924
+ if (p.compareTo(BigInteger.ONE) >= 0 && p.compareTo(BigInteger.valueOf(list.size())) <= 0) return list.get(p.intValue() - 1);
925
+ if (hasDflt) return dflt;
926
+ throw MissingValue("There is no item " + p + ": the list has " + list.size() + " item" + (list.size() == 1 ? "" : "s") + ".");
927
+ }
928
+ public static void setItem(Object items, Object position, Object value) { itemAt(items, position); asList(items).set(((BigInteger) position).intValue() - 1, value); }
929
+ public static void mapSet(Object m, Object k, Object v) {
930
+ if (m instanceof PyDict) { ((PyDict) m).set(k, v); return; }
931
+ if (m == null) throw TypeErr("'NoneType' object does not support item assignment");
932
+ if (isList(m)) { setItem(m, k, v); return; }
933
+ throw TypeErr("'" + (m instanceof Money ? "Money" : "object") + "' object does not support item assignment");
934
+ }
935
+ public static void setEntry(Object c, Object k, Object v) {
936
+ if (isList(c)) setItem(c, k, v);
937
+ else if (c instanceof PyDict) ((PyDict) c).set(k, v);
938
+ else if (c == null) throw MissingValue("This value is nothing, so it has no entry for " + show(k) + ".");
939
+ else throw KindMismatch(describe(c) + " has no entries that can be changed.");
940
+ }
941
+ public static Object entry(Object c, Object k) { return entry(c, k, false, null); }
942
+ public static Object entry(Object c, Object k, Object dflt) { return entry(c, k, true, dflt); }
943
+ static Object entry(Object c, Object k, boolean hasDflt, Object dflt) {
944
+ if (isList(c) || c instanceof Tuple) return itemAt(c, k, hasDflt, dflt);
945
+ if (c instanceof PyDict) { PyDict d = (PyDict) c; if (d.has(k)) return d.get(k); if (hasDflt) return dflt; throw MissingValue("There is no entry for " + show(k) + "."); }
946
+ if (c == null) throw MissingValue("This value is nothing, so it has no entry for " + show(k) + ".");
947
+ throw KindMismatch(describe(c) + " has no entries.");
948
+ }
949
+ public static Object mapGet(Object m, Object k) { return mapGet(m, k, false, null); }
950
+ public static Object mapGet(Object m, Object k, Object dflt) { return mapGet(m, k, true, dflt); }
951
+ static Object mapGet(Object m, Object k, boolean hasDflt, Object dflt) {
952
+ if (m instanceof PyDict) { PyDict d = (PyDict) m; if (d.has(k)) return d.get(k); if (hasDflt) return dflt; throw PyErr("KeyError", pyStr(k), Collections.singletonList(k)); }
953
+ if (m == null) throw hasDflt ? attrErr(m, "get") : TypeErr("'NoneType' object is not subscriptable");
954
+ if (hasDflt) throw attrErr(m, "get");
955
+ if (isList(m)) {
956
+ List<Object> xs = asList(m);
957
+ if (k instanceof BigInteger) { long i = ((BigInteger) k).longValue(); if (((BigInteger) k).bitLength() < 63 && i >= -xs.size() && i < xs.size()) return xs.get((int) (i < 0 ? xs.size() + i : i)); }
958
+ throw PyErr("IndexError", "list index out of range");
959
+ }
960
+ throw TypeErr("'" + (m instanceof Money ? "Money" : "object") + "' object is not subscriptable");
961
+ }
962
+
963
+ /** obj.name for a record field (a Python attribute), or Money's amount. */
964
+ public static Object getAttr(Object obj, String name) {
965
+ if (obj instanceof RecordVal && ((RecordVal) obj).f.containsKey(name)) return ((RecordVal) obj).f.get(name);
966
+ if (obj instanceof Money && name.equals("amount")) return ((Money) obj).amount;
967
+ throw attrErr(obj, name);
968
+ }
969
+
970
+ static String[] fieldNames(String key) { String low = key.toLowerCase(java.util.Locale.ROOT); return new String[] { key, key.replace(' ', '_'), low, low.replace(' ', '_') }; }
971
+
972
+ public static Object getField(Object obj, String key) {
973
+ if (obj == null) throw MissingValue("This value is nothing, so it has no " + key + ".");
974
+ String[] names = fieldNames(key);
975
+ if (obj instanceof PyDict) {
976
+ PyDict d = (PyDict) obj;
977
+ for (String k : names) if (d.has(k)) return d.get(k);
978
+ for (Object[] e : d.m.values()) if (pyStrip(pyStr(e[0])).toLowerCase(java.util.Locale.ROOT).equals(key.toLowerCase(java.util.Locale.ROOT))) return e[1];
979
+ StringBuilder b = new StringBuilder();
980
+ List<Object> ks = d.keys();
981
+ for (int i = 0; i < ks.size(); i++) { if (i > 0) b.append(", "); b.append(pyStr(ks.get(i))); }
982
+ throw MissingValue("There is no field \"" + key + "\". Fields here: " + b + ".");
983
+ }
984
+ for (String k : names) {
985
+ if (obj instanceof RecordVal && ((RecordVal) obj).f.containsKey(k)) return ((RecordVal) obj).f.get(k);
986
+ if (obj instanceof Money && k.equals("amount")) return ((Money) obj).amount;
987
+ }
988
+ throw MissingValue(describe(obj) + " has no field \"" + key + "\".");
989
+ }
990
+
991
+ public static Object addTo(Object target, Object value) { if (isList(target)) { asList(target).add(value); return target; } return add(target, value); }
992
+ public static void appendTo(Object target, Object value) { if (!isList(target)) throw attrErr(target, "append"); asList(target).add(value); }
993
+ public static void removeFrom(Object target, Object value) {
994
+ if (target instanceof PyDict) { PyDict d = (PyDict) target; if (!d.has(value)) throw MissingValue("There is no entry for " + show(value) + " to remove."); d.delete(value); return; }
995
+ if (!contains(target, value)) throw MissingValue(show(value) + " is not in the list, so it can't be removed.");
996
+ if (!isList(target)) throw attrErr(target, "remove");
997
+ List<Object> xs = asList(target);
998
+ for (int i = 0; i < xs.size(); i++) if (xs.get(i) == value || eq(xs.get(i), value)) { xs.remove(i); return; }
999
+ }
1000
+ public static void sortInPlace(Object target, Function<Object, Object> key, boolean desc) {
1001
+ if (!isList(target)) throw attrErr(target, "sort");
1002
+ ArrayList<Object> sorted = pySort(asList(target), key, desc);
1003
+ asList(target).clear();
1004
+ asList(target).addAll(sorted);
1005
+ }
1006
+ public static void reverseInPlace(Object target) { if (!isList(target)) throw attrErr(target, "reverse"); Collections.reverse(asList(target)); }
1007
+
1008
+ /** never(cond, text, rule, value): a broken Never rule stops the program. */
1009
+ public static void never(Object cond, String text, int line, Object value) {
1010
+ if (truthy(cond)) throw RuleBroken(text + " (the rule on line " + line + "), but the value is " + show(value) + ".");
1011
+ }
1012
+
1013
+ /** The operations written as words: the sum of, the first of, the words of, … */
1014
+ public static Object applyOp(String op, Object a) {
1015
+ switch (op) {
1016
+ case "sum": return totalOf(pyList(a));
1017
+ case "average": { List<Object> items = pyList(a); if (items.isEmpty()) throw MissingValue("I can't take the average of an empty list."); return divide(totalOf(items), BigInteger.valueOf(items.size())); }
1018
+ case "count": case "length": return pyLen(a);
1019
+ case "min": { List<Object> items = pyList(a); if (items.isEmpty()) throw MissingValue("An empty list has no smallest item."); Object best = items.get(0); for (int i = 1; i < items.size(); i++) if (compare("<", items.get(i), best)) best = items.get(i); return best; }
1020
+ case "max": { List<Object> items = pyList(a); if (items.isEmpty()) throw MissingValue("An empty list has no largest item."); Object best = items.get(0); for (int i = 1; i < items.size(); i++) if (compare(">", items.get(i), best)) best = items.get(i); return best; }
1021
+ case "first": { List<Object> items = pyList(a); if (items.isEmpty()) throw MissingValue("An empty list has no first item."); return items.get(0); }
1022
+ case "last": { List<Object> items = pyList(a); if (items.isEmpty()) throw MissingValue("An empty list has no last item."); return items.get(items.size() - 1); }
1023
+ case "words": { ArrayList<Object> out = new ArrayList<>(); for (Object p : pySplit(pyStr(a))) { String w = stripPunct((String) p); if (!w.isEmpty()) out.add(w); } return out; }
1024
+ case "lines": return splitLines(strMethod(a, "splitlines"));
1025
+ case "lowercase": return strMethod(a, "lower").toLowerCase(java.util.Locale.ROOT);
1026
+ case "uppercase": return strMethod(a, "upper").toUpperCase(java.util.Locale.ROOT);
1027
+ case "trimmed": return pyStrip(strMethod(a, "strip"));
1028
+ case "parts": return pySplit(textOf(a, "\"the parts of\""));
1029
+ case "abs": {
1030
+ if (a instanceof Money) return new Money(((Money) a).amount.abs());
1031
+ if (a instanceof Boolean || !isNumber(a)) throw KindMismatch("\"the absolute value of\" needs a number or money, but it is " + describe(a) + ".");
1032
+ return a instanceof BigInteger ? ((BigInteger) a).abs() : ((Dec) a).abs();
1033
+ }
1034
+ case "jsonText": return jsonText(a);
1035
+ case "jsonData": return jsonParse(textOf(a, "\"the JSON data in\""));
1036
+ case "keys": if (!(a instanceof PyDict)) throw attrErr(a, "keys"); return ((PyDict) a).keys();
1037
+ case "values": if (!(a instanceof PyDict)) throw attrErr(a, "values"); return ((PyDict) a).values();
1038
+ default: throw PyErr("NameError", "name '" + op + "' is not defined");
1039
+ }
1040
+ }
1041
+
1042
+ /** "starts with" / "ends with": both sides must be text. */
1043
+ public static boolean affix(Object t, Object a, boolean end) {
1044
+ String what = end ? "\"ends with\"" : "\"starts with\"";
1045
+ textOf(t, what); textOf(a, what);
1046
+ return end ? ((String) t).endsWith((String) a) : ((String) t).startsWith((String) a);
1047
+ }
1048
+
1049
+ /** a <= v <= hi, the way Python chains it: hi is worked out only when the first part holds. */
1050
+ public static boolean between(Object lo, Object v, Supplier<Object> hi) { if (!compare("<=", lo, v)) return false; return compare("<=", v, hi.get()); }
1051
+ /** `item in container`, with the item worked out first (as Python does). */
1052
+ public static boolean isIn(Object item, Object container) { return contains(container, item); }
1053
+
1054
+ /** Expect: the checks, the way thunder_runtime.py's expect_* do them. */
1055
+ public static void expectTrue(Object v, String text) { if (!Boolean.TRUE.equals(v)) throw ExpectationFailed(text + ", but it was not true."); }
1056
+ public static void expectFailure(Runnable run, String text, Object msg) {
1057
+ try { run.run(); }
1058
+ catch (RuntimeException | StackOverflowError e) {
1059
+ TErr err = asPyErr(e);
1060
+ if (err.thunder && msg != null) {
1061
+ if (!(msg instanceof String)) throw TypeErr("'in <string>' requires string as left operand, not " + (msg instanceof BigInteger ? "int" : "object"));
1062
+ if (!err.getMessage().contains((String) msg)) throw ExpectationFailed(text + ", but it failed with \"" + err.getMessage() + "\".");
1063
+ }
1064
+ return;
1065
+ }
1066
+ throw ExpectationFailed(text + ", but it did not fail.");
1067
+ }
1068
+ public static void expectValue(Object actual, String full, String op, Object want, String text) {
1069
+ boolean ok = CHECK_NAMES.contains(full) ? check(full, actual, want) : !check(op, actual, want);
1070
+ if (!ok) throw ExpectationFailed(text + ", but it was " + show(actual) + ".");
1071
+ }
1072
+ static final Set<String> CHECK_NAMES = new HashSet<>(Arrays.asList("is", "is not", "at least", "at most", "more than", "less than", "nothing", "not nothing", "empty", "positive", "negative", "zero", "between", "in", "contains"));
1073
+ static boolean check(String name, Object a, Object b) {
1074
+ switch (name) {
1075
+ case "is": return eq(a, b);
1076
+ case "is not": return !eq(a, b);
1077
+ case "at least": return compare(">=", a, b);
1078
+ case "at most": return compare("<=", a, b);
1079
+ case "more than": return compare(">", a, b);
1080
+ case "less than": return compare("<", a, b);
1081
+ case "nothing": return a == null;
1082
+ case "not nothing": return a != null;
1083
+ case "empty": return eq(pyLen(a), BigInteger.ZERO);
1084
+ case "positive": return compare(">", a, BigInteger.ZERO);
1085
+ case "negative": return compare("<", a, BigInteger.ZERO);
1086
+ case "zero": return eq(a, BigInteger.ZERO);
1087
+ case "between": { List<Object> r = asList(b); return compare("<=", r.get(0), a) && compare("<=", a, r.get(1)); }
1088
+ case "in": return contains(b, a);
1089
+ case "contains": return contains(a, b);
1090
+ default: throw new IllegalArgumentException(name);
1091
+ }
1092
+ }
1093
+
1094
+ /** describe_error(error) in thunder_runtime.py: "main.thunder, line 3 (reached from line 7): … [TC501]". */
1095
+ public static String describeError(TErr e) {
1096
+ List<Where> where = e.where != null ? e.where : Collections.emptyList();
1097
+ Where inner = where.isEmpty() ? null : where.get(where.size() - 1);
1098
+ String message = explain(e);
1099
+ String code = codeOf(e);
1100
+ if (code.equals("TC508") && !e.thunder) message = "Python code used by this line failed: " + message;
1101
+ String place = inner != null ? inner.file + ", line " + inner.line : "In the program";
1102
+ if (where.size() > 1 && inner != null) {
1103
+ StringBuilder b = new StringBuilder();
1104
+ for (int i = where.size() - 2; i >= 0; i--) { if (b.length() > 0) b.append(", then line "); b.append(where.get(i).line); }
1105
+ place += " (reached from line " + b + ")";
1106
+ }
1107
+ return place + ": " + message + " [" + code + "]";
1108
+ }
1109
+
1110
+ /** Values the generated code writes literally. */
1111
+ public static BigInteger i(String text) { return new BigInteger(text); }
1112
+ public static Dec dec(String text) { return Dec.parse(text); }
1113
+ public static Money money(String text) { return Money.of(text); }
1114
+ public static PyDate today() { return PyDate.todayDate(); }
1115
+ public static PyDate date(String text) { PyDate d = PyDate.parse(text); if (d == null) throw PyErr("ValueError", "Invalid isoformat string: '" + text + "'"); return d; }
1116
+ public static PyDict newMap() { return new PyDict(); }
1117
+ public static ArrayList<Object> list(Object... items) { return new ArrayList<>(Arrays.asList(items)); }
1118
+
1119
+ // ── conversions and text helpers (thunder_runtime.py) ──────────────────────────────────────────────────────────
1120
+
1121
+ static final Pattern NUMBER = Pattern.compile("^[+-]?(\\d[\\d_]*)(\\.\\d+)?$");
1122
+
1123
+ public static Object toNumber(Object x) {
1124
+ if (isNumber(x)) return x;
1125
+ if (x instanceof Money) return ((Money) x).amount;
1126
+ if (x instanceof String) {
1127
+ String s = pyStrip((String) x).replace(",", "");
1128
+ if (NUMBER.matcher(s).matches()) return s.contains(".") ? Dec.parse(s) : new BigInteger(s.replace("_", ""));
1129
+ }
1130
+ throw ConversionFailed(describe(x) + " is not a number.");
1131
+ }
1132
+ public static Object toWhole(Object x) {
1133
+ Object n = toNumber(x);
1134
+ if (n instanceof BigInteger) return n;
1135
+ Dec d = (Dec) n;
1136
+ if (d.isIntegral()) return d.toBigInt();
1137
+ throw ConversionFailed(show(n) + " is not a whole number.");
1138
+ }
1139
+ public static Object toMoney(Object x) {
1140
+ if (x instanceof Money) return x;
1141
+ if (x instanceof String) {
1142
+ String s = pyStrip((String) x).replace(",", "");
1143
+ boolean negative = s.startsWith("-");
1144
+ s = s.replaceAll("^-+", "").replaceAll("^\\$+", "");
1145
+ if (NUMBER.matcher(s).matches()) return Money.of((negative ? "-" : "") + s);
1146
+ throw ConversionFailed(describe(x) + " is not an amount of money.");
1147
+ }
1148
+ return new Money(toDec(toNumber(x)));
1149
+ }
1150
+ public static Object toYesNo(Object x) {
1151
+ if (x instanceof Boolean) return x;
1152
+ if (x instanceof String) {
1153
+ String t = pyStrip((String) x).toLowerCase(java.util.Locale.ROOT);
1154
+ if (t.equals("yes") || t.equals("true")) return true;
1155
+ if (t.equals("no") || t.equals("false")) return false;
1156
+ }
1157
+ throw ConversionFailed(describe(x) + " is not yes or no.");
1158
+ }
1159
+ public static Object toDate(Object x) {
1160
+ if (x instanceof PyDate) return x;
1161
+ PyDate d = PyDate.parse(pyStrip(pyStr(x)));
1162
+ if (d != null) return d;
1163
+ throw ConversionFailed(describe(x) + " is not a date (write it as YYYY-MM-DD).");
1164
+ }
1165
+
1166
+ static Object totalOf(List<Object> items) {
1167
+ if (items.isEmpty()) return BigInteger.ZERO;
1168
+ Object result = items.get(0);
1169
+ for (int i = 1; i < items.size(); i++) result = add(result, items.get(i));
1170
+ return result;
1171
+ }
1172
+ static String textOf(Object v, String what) {
1173
+ if (!(v instanceof String)) throw KindMismatch(what + " needs text, but it is " + describe(v) + ".");
1174
+ return (String) v;
1175
+ }
1176
+ public static String joined(Object items, Object sep) {
1177
+ String sp = textOf(sep, "\"joined with\"");
1178
+ StringBuilder b = new StringBuilder();
1179
+ List<Object> xs = pyIter(items);
1180
+ for (int i = 0; i < xs.size(); i++) {
1181
+ Object x = xs.get(i);
1182
+ if (!(x instanceof String)) throw KindMismatch("\"joined with\" joins text, but item " + (i + 1) + " is " + describe(x) + ". Turn it into text first.");
1183
+ if (i > 0) b.append(sp);
1184
+ b.append((String) x);
1185
+ }
1186
+ return b.toString();
1187
+ }
1188
+ public static ArrayList<Object> splitAt(Object text, Object sep) {
1189
+ String sp = textOf(sep, "\"split at\"");
1190
+ if (sp.isEmpty()) throw KindMismatch("\"split at\" needs something to split at, not empty text.");
1191
+ String t = textOf(text, "\"split at\"");
1192
+ ArrayList<Object> out = new ArrayList<>();
1193
+ int from = 0;
1194
+ for (;;) { int at = t.indexOf(sp, from); if (at < 0) { out.add(t.substring(from)); return out; } out.add(t.substring(from, at)); from = at + sp.length(); }
1195
+ }
1196
+ public static String replacing(Object text, Object old, Object nw) {
1197
+ String o = textOf(old, "\"replacing\"");
1198
+ if (o.isEmpty()) throw KindMismatch("\"replacing\" needs something to replace, not empty text.");
1199
+ String t = textOf(text, "\"replacing\"");
1200
+ String w = textOf(nw, "\"replacing … with\"");
1201
+ return t.replace(o, w);
1202
+ }
1203
+ static final Set<Integer> PUNCT = new HashSet<>();
1204
+ static { ".,;:!?\"'()[]{}<>“”‘’…-".codePoints().forEach(PUNCT::add); }
1205
+ static String stripPunct(String w) {
1206
+ int[] a = w.codePoints().toArray();
1207
+ int i = 0, j = a.length;
1208
+ while (i < j && PUNCT.contains(a[i])) i++;
1209
+ while (j > i && PUNCT.contains(a[j - 1])) j--;
1210
+ return new String(a, i, j - i);
1211
+ }
1212
+
1213
+ // ── Running compiled Java: frames (for error lines), output, files, and the program or its tests ───────────────
1214
+
1215
+ /** A call frame: the Thunder file and the line it is on. */
1216
+ public static final class Frame { public final String file; public int line; Frame(String file, int line) { this.file = file; this.line = line; } }
1217
+
1218
+ static final ArrayList<Frame> frames = new ArrayList<>();
1219
+ static boolean aborted = false;
1220
+ static int exitCode = 0;
1221
+ /** Output goes through UTF-8 streams of its own (System.out's encoding depends on the machine). */
1222
+ public static PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out), true, StandardCharsets.UTF_8);
1223
+ public static PrintStream err = new PrintStream(new FileOutputStream(FileDescriptor.err), true, StandardCharsets.UTF_8);
1224
+
1225
+ static List<Where> snapshot() { ArrayList<Where> w = new ArrayList<>(); for (Frame f : frames) w.add(new Where(f.file, f.line)); return w; }
1226
+
1227
+ /** A frame for a program, a test, or a kept value. */
1228
+ public static Frame enterFrame(String file, int line) {
1229
+ if (frames.size() >= MAX_FRAMES) throw PyErr("RecursionError", "maximum recursion depth exceeded");
1230
+ Frame f = new Frame(file, line);
1231
+ frames.add(f);
1232
+ return f;
1233
+ }
1234
+ /** A frame for a call; `first` is the Thunder line the function starts on (where Python stops when it is too deep). */
1235
+ public static Frame enterCall(String file, int line, Integer first) {
1236
+ if (frames.size() >= MAX_FRAMES) {
1237
+ TErr e = PyErr("RecursionError", "maximum recursion depth exceeded");
1238
+ if (first != null) { List<Where> w = snapshot(); w.add(new Where(file, first)); e.where = w; }
1239
+ throw e;
1240
+ }
1241
+ Frame f = new Frame(file, line);
1242
+ frames.add(f);
1243
+ return f;
1244
+ }
1245
+ public static void leave() { frames.remove(frames.size() - 1); }
1246
+ /** The innermost frame (a record's Never rule runs in its caller's frame). */
1247
+ public static Frame topFrame() { return frames.get(frames.size() - 1); }
1248
+ /** An error on its way out of a frame: remember where it happened (the innermost frames first seen). */
1249
+ public static TErr fail(Throwable e) { TErr t = asPyErr(e); if (t.where == null) t.where = snapshot(); return t; }
1250
+ static Object withFrame(Frame frame, Supplier<Object> fn) {
1251
+ if (frames.size() >= MAX_FRAMES) throw PyErr("RecursionError", "maximum recursion depth exceeded");
1252
+ frames.add(frame);
1253
+ try { return fn.get(); } catch (RuntimeException e) { throw fail(e); } finally { frames.remove(frames.size() - 1); }
1254
+ }
1255
+ /** A key for sorting by a field: it runs in a frame at the sorting line, as the generated Python's lambda does. */
1256
+ public static Function<Object, Object> keyAt(Frame F, Function<Object, Object> get) {
1257
+ Frame frame = new Frame(F.file, F.line);
1258
+ return (item) -> withFrame(frame, () -> get.apply(item));
1259
+ }
1260
+ /** Sets the frame's line, then goes on (for a condition: the line is set before the condition is worked out). */
1261
+ public static boolean at(Frame F, int line) { F.line = line; return true; }
1262
+ /** An expression worked out for what it does (a call), its value not kept. */
1263
+ public static void discard(Object v) {}
1264
+
1265
+ /** One part of a map entry (a key and its value): 0 is the key, 1 the value. */
1266
+ public static Object pairPart(Object entry, int i) { return ((Tuple) entry).items.get(i); }
1267
+ public static ArrayList<Object> filter(List<Object> items, Predicate<Object> keep) { ArrayList<Object> out = new ArrayList<>(); for (Object x : items) if (keep.test(x)) out.add(x); return out; }
1268
+ public static ArrayList<Object> map(List<Object> items, Function<Object, Object> get) { ArrayList<Object> out = new ArrayList<>(); for (Object x : items) out.add(get.apply(x)); return out; }
1269
+
1270
+ public static void say(String text) { out.print(text + "\n"); }
1271
+ /** The folder the program runs in, where it reads files (thunder.cwd when Thunder runs it elsewhere). */
1272
+ static Path cwd() { return Paths.get(System.getProperty("thunder.cwd", System.getProperty("user.dir"))); }
1273
+ public static String readText(Object path) {
1274
+ if (!(path instanceof String)) throw TypeErr("expected str, bytes or os.PathLike object, not " + (path == null ? "NoneType" : "object"));
1275
+ String p = (String) path;
1276
+ try {
1277
+ Path full = cwd().resolve(p);
1278
+ if (Files.isDirectory(full)) throw PyErr("IsADirectoryError", "EISDIR: illegal operation on a directory, read");
1279
+ return new String(Files.readAllBytes(full), StandardCharsets.UTF_8);
1280
+ } catch (NoSuchFileException e) {
1281
+ throw MissingValue("There is no file \"" + p + "\" (looked in the folder the program runs in).");
1282
+ } catch (IOException e) {
1283
+ throw PyErr("OSError", String.valueOf(e.getMessage()));
1284
+ }
1285
+ }
1286
+
1287
+ /** Records: their kind (name, fields, and Never rules), making one, and setting a field. */
1288
+ public static RecordKind recordKind(String py, Field[] fields, Map<String, List<Rule>> rules) { return new RecordKind(py, Arrays.asList(fields), rules); }
1289
+ public static RecordKind recordKind(String py, Field[] fields) { return new RecordKind(py, Arrays.asList(fields), new HashMap<>()); }
1290
+ public static Map<String, List<Rule>> rules(Object... pairs) { Map<String, List<Rule>> m = new HashMap<>(); for (int i = 0; i < pairs.length; i += 2) m.put((String) pairs[i], Arrays.asList((Rule[]) pairs[i + 1])); return m; }
1291
+ public static void setAttr(Object obj, String name, Object value) {
1292
+ if (obj instanceof RecordVal) {
1293
+ RecordVal rec = (RecordVal) obj;
1294
+ List<Rule> rs = rec.cls.rules.get(name);
1295
+ if (rs != null) for (Rule r : rs) never(r.cond.apply(value), r.text, r.line, value);
1296
+ rec.f.put(name, value);
1297
+ return;
1298
+ }
1299
+ if (obj instanceof Money) throw PyErr("AttributeError", "Money cannot be changed; make new money instead.");
1300
+ throw attrErr(obj, name);
1301
+ }
1302
+ public static void setField(Object obj, String key, Object value) {
1303
+ if (obj instanceof PyDict) { ((PyDict) obj).set(key, value); return; }
1304
+ for (String k : fieldNames(key)) if (obj instanceof RecordVal && ((RecordVal) obj).f.containsKey(k)) { setAttr(obj, k, value); return; }
1305
+ throw MissingValue(describe(obj) + " has no field \"" + key + "\".");
1306
+ }
1307
+ /** A record: the fields it is given, the others defaulted; each set through setAttr (its Never rules). */
1308
+ public static RecordVal newRecord(RecordKind cls, Object... pairs) {
1309
+ LinkedHashMap<String, Object> given = new LinkedHashMap<>();
1310
+ for (int i = 0; i < pairs.length; i += 2) given.put((String) pairs[i], pairs[i + 1]);
1311
+ RecordVal rec = new RecordVal(cls);
1312
+ ArrayList<String> missing = new ArrayList<>();
1313
+ for (Field f : cls.fields) if (!given.containsKey(f.py) && !f.kind.equals("optional") && !f.kind.equals("list") && !f.kind.equals("map")) missing.add("'" + f.py + "'");
1314
+ if (!missing.isEmpty()) throw TypeErr(cls.py + ".__init__() missing " + missing.size() + " required keyword-only argument" + (missing.size() == 1 ? "" : "s") + ": " + String.join(missing.size() == 2 ? " and " : ", ", missing));
1315
+ for (Field f : cls.fields) {
1316
+ Object v = given.containsKey(f.py) ? given.get(f.py) : f.kind.equals("optional") ? null : f.kind.equals("list") ? new ArrayList<Object>() : new PyDict();
1317
+ setAttr(rec, f.py, v);
1318
+ }
1319
+ return rec;
1320
+ }
1321
+
1322
+ static void report(Throwable e) { err.print(describeError(asPyErr(e)) + "\n"); exitCode = 1; aborted = true; }
1323
+ /** A body that works out a file's kept values. */
1324
+ public interface KeptValues { void run(Frame F); }
1325
+ /** Work out a file's kept values; an error stops the program with a Thunder message. */
1326
+ public static void init(String file, KeptValues fn) {
1327
+ if (aborted) return;
1328
+ Frame F = new Frame(file, 0);
1329
+ try { withFrame(F, () -> { fn.run(F); return null; }); } catch (RuntimeException e) { report(e); }
1330
+ }
1331
+
1332
+ /** Python allows about 1000 nested calls; the program runs on a thread with a stack deep enough for that. */
1333
+ static void onBigStack(Runnable body) {
1334
+ Throwable[] crash = { null };
1335
+ Thread t = new Thread(null, () -> { try { body.run(); } catch (Throwable e) { crash[0] = e; } }, "thunder", 1L << 30);
1336
+ t.start();
1337
+ try { t.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
1338
+ if (crash[0] instanceof RuntimeException) throw (RuntimeException) crash[0];
1339
+ if (crash[0] instanceof Error) throw (Error) crash[0];
1340
+ }
1341
+
1342
+ /** Run the program; stop with exit code 1 after an error, as `python main.py` does. */
1343
+ public static void run(Runnable main) {
1344
+ if (!aborted) onBigStack(() -> { try { main.run(); } catch (RuntimeException | StackOverflowError e) { report(e); } });
1345
+ finish();
1346
+ }
1347
+ /** Every Test block, the way run_tests.py runs them: one line per test, then the totals. */
1348
+ public static void runTests(Object[][] modules) {
1349
+ if (!aborted) onBigStack(() -> {
1350
+ int passed = 0, failed = 0;
1351
+ for (Object[] mod : modules) {
1352
+ String file = (String) mod[0];
1353
+ for (Object[] t : (Object[][]) mod[1]) {
1354
+ String title = (String) t[0]; Runnable fn = (Runnable) t[1]; int line = (Integer) t[2];
1355
+ try { fn.run(); passed++; say("PASS " + title + " (" + file + ", line " + line + ")"); }
1356
+ catch (RuntimeException | StackOverflowError e) { failed++; say("FAIL " + title + " (" + file + ", line " + line + ")"); say(" " + describeError(asPyErr(e))); }
1357
+ }
1358
+ }
1359
+ int total = passed + failed;
1360
+ say(total + " test" + (total == 1 ? "" : "s") + ": " + passed + " passed, " + failed + " failed");
1361
+ if (failed > 0) exitCode = 1;
1362
+ });
1363
+ finish();
1364
+ }
1365
+
1366
+ /** Embedded (Thunder runs many programs in one Java process): finishing records the exit code instead of exiting. */
1367
+ public static boolean embedded = Boolean.getBoolean("thunder.embedded");
1368
+ static void finish() {
1369
+ out.flush(); err.flush();
1370
+ if (!embedded) System.exit(exitCode);
1371
+ }
1372
+ /** The exit code (for an embedding process), and a fresh start for the next program. */
1373
+ public static int takeExitCode() { int c = exitCode; exitCode = 0; aborted = false; frames.clear(); return c; }
1374
+ }