@skillstech/thunderlang 1.0.4 → 1.2.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.
- package/CHANGELOG.md +221 -0
- package/README.md +4 -1
- package/dist/core.cjs +2568 -462
- package/dist/index.cjs +7562 -5084
- package/dist/learn.cjs +16994 -8339
- package/intent-graph.schema.json +11 -0
- package/package.json +6 -2
- package/src/cli-home.mjs +242 -0
- package/src/cli.mjs +241 -89
- package/src/codegen.mjs +145 -55
- package/src/conformance.mjs +15 -6
- package/src/core/check.mjs +725 -0
- package/src/core/cli.mjs +184 -0
- package/src/core/diagnostics.mjs +82 -0
- package/src/core/engine-core.mjs +572 -0
- package/src/core/engine-values.mjs +1054 -0
- package/src/core/engine-worker.mjs +15 -0
- package/src/core/engine.mjs +63 -0
- package/src/core/format.mjs +20 -0
- package/src/core/from-python.mjs +645 -0
- package/src/core/index.mjs +39 -0
- package/src/core/lexer.mjs +115 -0
- package/src/core/parser.mjs +742 -0
- package/src/core/project.mjs +177 -0
- package/src/core/round-trip.mjs +150 -0
- package/src/core/runtime-python.mjs +801 -0
- package/src/core/runtime-typescript.mjs +119 -0
- package/src/core/target-python.mjs +487 -0
- package/src/core/target-typescript.mjs +466 -0
- package/src/core/typescript-run.mjs +114 -0
- package/src/core.d.ts +5 -2
- package/src/core.mjs +5 -2
- package/src/data-schema.mjs +8 -1
- package/src/emit.mjs +1 -1
- package/src/evidence.mjs +1 -1
- package/src/expr.mjs +81 -4
- package/src/form-words.mjs +2 -0
- package/src/index.d.ts +8 -1
- package/src/index.mjs +5 -1
- package/src/intent-schema.mjs +1 -0
- package/src/learn-lessons.mjs +245 -1
- package/src/learn.d.mts +8 -0
- package/src/learn.mjs +40 -4
- package/src/mcp.mjs +23 -0
- package/src/meaning.mjs +45 -6
- package/src/model.d.mts +7 -3
- package/src/model.mjs +19 -6
- package/src/money.d.mts +18 -0
- package/src/money.mjs +124 -0
- package/src/plain-contract.mjs +18 -2
- package/src/read-level.mjs +146 -0
- package/src/read.d.mts +11 -0
- package/src/read.mjs +40 -6
- package/src/review-comment.d.mts +16 -0
- package/src/review-comment.mjs +145 -0
- package/src/say-less.mjs +1432 -0
- package/src/system.mjs +153 -44
- package/src/target-cs.mjs +39 -34
- package/src/target-elixir.mjs +40 -30
- package/src/target-go.mjs +41 -36
- package/src/target-java.mjs +34 -27
- package/src/target-kotlin.mjs +43 -35
- package/src/target-py.mjs +57 -55
- package/src/target-result.d.mts +48 -0
- package/src/target-result.mjs +112 -0
- package/src/target-rust.mjs +42 -38
- package/src/target-scala.mjs +45 -35
- package/src/target-ts.mjs +37 -45
- package/src/target-types.mjs +41 -5
- package/src/target-util.mjs +55 -2
- package/src/term.mjs +89 -0
- package/src/trace-cli.mjs +58 -0
- package/src/trace-fs.mjs +76 -0
- package/src/trace.mjs +261 -0
- package/src/translate.d.mts +3 -0
- package/src/translate.mjs +62 -32
- package/src/try-cli.mjs +225 -0
- package/src/why-cli.mjs +41 -0
- package/src/why.d.mts +38 -0
- package/src/why.mjs +613 -0
- package/src/write-steps.mjs +22 -5
|
@@ -0,0 +1,1054 @@
|
|
|
1
|
+
// The values of the Thunder engine (src/core/engine.mjs) and the rules they follow.
|
|
2
|
+
//
|
|
3
|
+
// The Thunder engine runs Thunder Core without Python. Its behavior is defined by the Python target: the code
|
|
4
|
+
// target-python.mjs writes and thunder_runtime.py (runtime-python.mjs). Every value here behaves the way the
|
|
5
|
+
// generated Python behaves, including what an error says, so the two engines give the same output for the same
|
|
6
|
+
// program (compiler/test/core-engine.test.mjs runs every Core test program on both and compares).
|
|
7
|
+
//
|
|
8
|
+
// Values: whole number -> BigInt decimal number -> Dec (exact, like Python's Decimal)
|
|
9
|
+
// money -> Money text -> string yes/no -> boolean nothing -> null
|
|
10
|
+
// list -> Array (a pair from a map is a Tuple) map -> PyDict
|
|
11
|
+
// record -> RecordVal date -> PyDate
|
|
12
|
+
|
|
13
|
+
// ── Errors ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
14
|
+
|
|
15
|
+
/** An error the Python runtime raises as a ThunderError subclass (code TC5xx, message in words). */
|
|
16
|
+
export class ThunderErr extends Error {
|
|
17
|
+
constructor(code, message, pyType = 'ThunderError') { super(message); this.code = code; this.pyType = pyType; this.thunder = true; }
|
|
18
|
+
}
|
|
19
|
+
export const Stop = (m) => new ThunderErr('TC507', m, 'Stop');
|
|
20
|
+
export const RuleBroken = (m) => new ThunderErr('TC504', m, 'RuleBroken');
|
|
21
|
+
export const ExpectationFailed = (m) => new ThunderErr('TC505', m, 'ExpectationFailed');
|
|
22
|
+
export const KindMismatch = (m) => new ThunderErr('TC506', m, 'TypeError'); // also a TypeError
|
|
23
|
+
export const ConversionFailed = (m) => new ThunderErr('TC509', m, 'ValueError');
|
|
24
|
+
export const MissingValue = (m) => new ThunderErr('TC503', m, 'LookupError');
|
|
25
|
+
export const DividedByZero = (m) => new ThunderErr('TC501', m, 'ZeroDivisionError');
|
|
26
|
+
|
|
27
|
+
/** An error Python itself raises (TypeError, KeyError, ...), with Python's own message. */
|
|
28
|
+
export class PyErr extends Error {
|
|
29
|
+
constructor(pyType, message, args) { super(message); this.pyType = pyType; this.args = args ?? [message]; }
|
|
30
|
+
}
|
|
31
|
+
export const TypeErr = (m) => new PyErr('TypeError', m);
|
|
32
|
+
|
|
33
|
+
/** explain(error) in thunder_runtime.py: the error as a sentence. */
|
|
34
|
+
export function explain(e) {
|
|
35
|
+
if (e.thunder) return e.message;
|
|
36
|
+
const t = e.pyType;
|
|
37
|
+
if (t === 'ZeroDivisionError' || t === 'DivisionByZero') return 'You divided by zero.';
|
|
38
|
+
if (t === 'InvalidOperation') return 'This calculation has no answer (for example, zero divided by zero).';
|
|
39
|
+
if (t === 'KeyError') return `There is no entry for ${show(e.args[0] ?? null)}.`;
|
|
40
|
+
if ((t === 'TypeError' || t === 'AttributeError') && e.message.includes('NoneType')) return 'A value was nothing where a value was needed.';
|
|
41
|
+
if (t === 'TypeError') return `Values of different kinds were mixed (${e.message}).`;
|
|
42
|
+
if (t === 'RecursionError') return 'A function called itself too many times.';
|
|
43
|
+
return `${t}: ${e.message}`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** _code(error) in thunder_runtime.py. */
|
|
47
|
+
export function codeOf(e) {
|
|
48
|
+
if (e.thunder) return e.code;
|
|
49
|
+
const t = e.pyType;
|
|
50
|
+
if (t === 'ZeroDivisionError' || t === 'DivisionByZero') return 'TC501';
|
|
51
|
+
if ((t === 'TypeError' || t === 'AttributeError') && e.message.includes('NoneType')) return 'TC502';
|
|
52
|
+
if (t === 'KeyError') return 'TC503';
|
|
53
|
+
if (t === 'TypeError') return 'TC506';
|
|
54
|
+
return 'TC508';
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A JS error that is not a Thunder or Python error (a bug in the engine, or the JS stack running out). */
|
|
58
|
+
export function asPyErr(e) {
|
|
59
|
+
if (e instanceof ThunderErr || e instanceof PyErr) return e;
|
|
60
|
+
if (e instanceof RangeError && /call stack/i.test(e.message)) return new PyErr('RecursionError', 'maximum recursion depth exceeded');
|
|
61
|
+
throw e;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// ── Exact decimals: Python's Decimal with its default context (28 digits, half-even when a result is too long) ──
|
|
65
|
+
|
|
66
|
+
const PREC = 28;
|
|
67
|
+
const TEN = 10n;
|
|
68
|
+
const pow10 = (n) => TEN ** BigInt(n);
|
|
69
|
+
const ndigits = (c) => (c === 0n ? 1 : c.toString().length);
|
|
70
|
+
|
|
71
|
+
export class Dec {
|
|
72
|
+
constructor(s, c, e) { this.s = s; this.c = c; this.e = e; } // sign (0 or 1), coefficient >= 0, exponent
|
|
73
|
+
static of(x) { return x instanceof Dec ? x : typeof x === 'bigint' ? Dec.int(x) : typeof x === 'boolean' ? Dec.int(x ? 1n : 0n) : x; }
|
|
74
|
+
static int(n) { return new Dec(n < 0n ? 1 : 0, n < 0n ? -n : n, 0); }
|
|
75
|
+
/** Decimal("text"): exact. Returns null when the text is not a number. */
|
|
76
|
+
static parse(text) {
|
|
77
|
+
const m = String(text).trim().replace(/_/g, '').match(/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/);
|
|
78
|
+
if (!m || (!m[2] && !m[3])) return null;
|
|
79
|
+
const frac = m[3] ?? '';
|
|
80
|
+
return new Dec(m[1] === '-' ? 1 : 0, BigInt((m[2] || '') + frac || '0'), (m[4] ? Number(m[4]) : 0) - frac.length);
|
|
81
|
+
}
|
|
82
|
+
isZero() { return this.c === 0n; }
|
|
83
|
+
/** _fix: round to 28 significant digits, half to even. */
|
|
84
|
+
fix() {
|
|
85
|
+
const d = ndigits(this.c) - PREC;
|
|
86
|
+
if (d <= 0) return this;
|
|
87
|
+
const p = pow10(d);
|
|
88
|
+
let q = this.c / p;
|
|
89
|
+
const r = this.c % p, half = 5n * pow10(d - 1);
|
|
90
|
+
if (r > half || (r === half && q % 2n === 1n)) q += 1n;
|
|
91
|
+
let e = this.e + d;
|
|
92
|
+
if (ndigits(q) > PREC) { q /= TEN; e += 1; }
|
|
93
|
+
return new Dec(this.s, q, e);
|
|
94
|
+
}
|
|
95
|
+
signed() { return this.s ? -this.c : this.c; }
|
|
96
|
+
static add(a, b) {
|
|
97
|
+
const e = Math.min(a.e, b.e);
|
|
98
|
+
const x = a.signed() * pow10(a.e - e), y = b.signed() * pow10(b.e - e);
|
|
99
|
+
const sum = x + y;
|
|
100
|
+
let s;
|
|
101
|
+
if (sum === 0n) s = a.s === 1 && b.s === 1 && a.c === 0n && b.c === 0n ? 1 : (a.c === 0n && b.c === 0n ? Math.min(a.s, b.s) : 0);
|
|
102
|
+
else s = sum < 0n ? 1 : 0;
|
|
103
|
+
return new Dec(s, sum < 0n ? -sum : sum, e).fix();
|
|
104
|
+
}
|
|
105
|
+
negated() { return new Dec(this.s ? 0 : 1, this.c, this.e); }
|
|
106
|
+
static sub(a, b) { return Dec.add(a, b.negated()); }
|
|
107
|
+
static mul(a, b) { return new Dec(a.s ^ b.s, a.c * b.c, a.e + b.e).fix(); }
|
|
108
|
+
/** Python's Decimal division: exact when it can be, else 28 digits. */
|
|
109
|
+
static div(a, b) {
|
|
110
|
+
const s = a.s ^ b.s;
|
|
111
|
+
if (a.c === 0n) return new Dec(s, 0n, a.e - b.e).fix();
|
|
112
|
+
const shift = ndigits(b.c) - ndigits(a.c) + PREC + 1;
|
|
113
|
+
let exp = a.e - b.e - shift;
|
|
114
|
+
let coeff, rem;
|
|
115
|
+
if (shift >= 0) { const n = a.c * pow10(shift); coeff = n / b.c; rem = n % b.c; }
|
|
116
|
+
else { const d = b.c * pow10(-shift); coeff = a.c / d; rem = a.c % d; }
|
|
117
|
+
if (rem !== 0n) { if (coeff % 5n === 0n) coeff += 1n; }
|
|
118
|
+
else { const ideal = a.e - b.e; while (exp < ideal && coeff % TEN === 0n) { coeff /= TEN; exp += 1; } }
|
|
119
|
+
return new Dec(s, coeff, exp).fix();
|
|
120
|
+
}
|
|
121
|
+
/** Decimal % Decimal: the remainder with the sign of the dividend. */
|
|
122
|
+
static rem(a, b) {
|
|
123
|
+
const e = Math.min(a.e, b.e);
|
|
124
|
+
const x = a.c * pow10(a.e - e), y = b.c * pow10(b.e - e);
|
|
125
|
+
return new Dec(a.s, x % y, e).fix();
|
|
126
|
+
}
|
|
127
|
+
neg() { return (this.c === 0n ? new Dec(0, 0n, this.e) : this.negated()).fix(); }
|
|
128
|
+
abs() { return new Dec(0, this.c, this.e).fix(); }
|
|
129
|
+
static cmp(a, b) {
|
|
130
|
+
const e = Math.min(a.e, b.e);
|
|
131
|
+
const x = a.signed() * pow10(a.e - e), y = b.signed() * pow10(b.e - e);
|
|
132
|
+
return x < y ? -1 : x > y ? 1 : 0;
|
|
133
|
+
}
|
|
134
|
+
/** quantize to exponent `e` rounding half away from zero. */
|
|
135
|
+
quantizeHalfUp(e) {
|
|
136
|
+
if (e <= this.e) return new Dec(this.s, this.c * pow10(this.e - e), e);
|
|
137
|
+
const p = pow10(e - this.e);
|
|
138
|
+
let q = this.c / p;
|
|
139
|
+
if ((this.c % p) * 2n >= p) q += 1n;
|
|
140
|
+
return new Dec(this.s, q, e);
|
|
141
|
+
}
|
|
142
|
+
isIntegral() { if (this.e >= 0) return true; return this.c % pow10(-this.e) === 0n; }
|
|
143
|
+
/** int(d): toward zero. */
|
|
144
|
+
toBigInt() { const v = this.e >= 0 ? this.c * pow10(this.e) : this.c / pow10(-this.e); return this.s ? -v : v; }
|
|
145
|
+
/** str(Decimal): Python's to-scientific-string. */
|
|
146
|
+
toString() {
|
|
147
|
+
const digits = this.c.toString();
|
|
148
|
+
const left = this.e + digits.length;
|
|
149
|
+
const dot = this.e <= 0 && left > -6 ? left : 1;
|
|
150
|
+
let ip, fp;
|
|
151
|
+
if (dot <= 0) { ip = '0'; fp = `.${'0'.repeat(-dot)}${digits}`; }
|
|
152
|
+
else if (dot >= digits.length) { ip = digits + '0'.repeat(dot - digits.length); fp = ''; }
|
|
153
|
+
else { ip = digits.slice(0, dot); fp = `.${digits.slice(dot)}`; }
|
|
154
|
+
const ex = left === dot ? '' : `E${left - dot >= 0 ? '+' : ''}${left - dot}`;
|
|
155
|
+
return `${this.s ? '-' : ''}${ip}${fp}${ex}`;
|
|
156
|
+
}
|
|
157
|
+
/** format(d, "f") or format(d, ",.Nf"). */
|
|
158
|
+
toFixed(places = null, group = false) {
|
|
159
|
+
let d = this;
|
|
160
|
+
if (places != null) d = d.roundHalfEven(-places);
|
|
161
|
+
const digits = d.c.toString();
|
|
162
|
+
const dot = d.e + digits.length;
|
|
163
|
+
let ip, fp;
|
|
164
|
+
if (dot < 0) { ip = '0'; fp = '0'.repeat(-dot) + digits; }
|
|
165
|
+
else if (dot > digits.length) { ip = digits + '0'.repeat(dot - digits.length); fp = ''; }
|
|
166
|
+
else { ip = digits.slice(0, dot) || '0'; fp = digits.slice(dot); }
|
|
167
|
+
if (group) ip = ip.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
|
168
|
+
return `${d.s ? '-' : ''}${ip}${fp ? `.${fp}` : ''}`;
|
|
169
|
+
}
|
|
170
|
+
roundHalfEven(e) {
|
|
171
|
+
if (e <= this.e) return new Dec(this.s, this.c * pow10(this.e - e), e);
|
|
172
|
+
const p = pow10(e - this.e);
|
|
173
|
+
let q = this.c / p;
|
|
174
|
+
const r = this.c % p;
|
|
175
|
+
if (r * 2n > p || (r * 2n === p && q % 2n === 1n)) q += 1n;
|
|
176
|
+
return new Dec(this.s, q, e);
|
|
177
|
+
}
|
|
178
|
+
/** A key equal for equal numbers (1 and 1.0 and 1.00 are the same map key, as in Python). */
|
|
179
|
+
key() {
|
|
180
|
+
if (this.c === 0n) return '0';
|
|
181
|
+
let c = this.c, e = this.e;
|
|
182
|
+
while (c % TEN === 0n) { c /= TEN; e += 1; }
|
|
183
|
+
return `${this.s ? '-' : ''}${c}e${e}`;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// ── Money ──────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
188
|
+
|
|
189
|
+
export class Money {
|
|
190
|
+
constructor(amount) { this.amount = amount; }
|
|
191
|
+
static of(x) {
|
|
192
|
+
if (x instanceof Money) return x;
|
|
193
|
+
if (typeof x === 'string') {
|
|
194
|
+
const d = Dec.parse(x.replace(/,/g, '').replace(/\$/g, '').trim());
|
|
195
|
+
if (!d) throw new PyErr('InvalidOperation', "[<class 'decimal.ConversionSyntax'>]");
|
|
196
|
+
return new Money(d);
|
|
197
|
+
}
|
|
198
|
+
return new Money(toDec(x));
|
|
199
|
+
}
|
|
200
|
+
toString() {
|
|
201
|
+
const a = this.amount;
|
|
202
|
+
const places = a.e < 0 ? Math.max(2, -a.e) : 2;
|
|
203
|
+
return `${a.s && a.c !== 0n ? '-$' : '$'}${a.abs().toFixed(places, true)}`;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Money._other: the amount of the other side, or a clear error. */
|
|
208
|
+
function moneyOther(other, verb) {
|
|
209
|
+
if (other instanceof Money) return other.amount;
|
|
210
|
+
if (isNumber(other) && numCmp(other, 0n) === 0) return Dec.int(0n);
|
|
211
|
+
throw KindMismatch(`I can't ${verb} money and ${describe(other)}. Write the number as money, for example $5.`);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ── Other kinds ────────────────────────────────────────────────────────────────────────────────────────────────
|
|
215
|
+
|
|
216
|
+
export class PyDate {
|
|
217
|
+
constructor(y, m, d) { this.y = y; this.m = m; this.d = d; }
|
|
218
|
+
iso() { return `${String(this.y).padStart(4, '0')}-${String(this.m).padStart(2, '0')}-${String(this.d).padStart(2, '0')}`; }
|
|
219
|
+
num() { return this.y * 10000 + this.m * 100 + this.d; }
|
|
220
|
+
static today() { const t = new Date(); return new PyDate(t.getFullYear(), t.getMonth() + 1, t.getDate()); }
|
|
221
|
+
/** date.fromisoformat for YYYY-MM-DD (and YYYYMMDD); null when it is not a date. */
|
|
222
|
+
static parse(text) {
|
|
223
|
+
const m = String(text).match(/^(\d{4})-?(\d{2})-?(\d{2})$/);
|
|
224
|
+
if (!m) return null;
|
|
225
|
+
const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
|
|
226
|
+
const days = [31, (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0 ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
227
|
+
if (y < 1 || mo < 1 || mo > 12 || d < 1 || d > days[mo - 1]) return null;
|
|
228
|
+
return new PyDate(y, mo, d);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export class Tuple { constructor(items) { this.items = items; } }
|
|
233
|
+
|
|
234
|
+
export const NOT_GIVEN = Object.freeze({ notGiven: true });
|
|
235
|
+
|
|
236
|
+
/** A Python dict: insertion order kept; keys equal the way Python compares them (1 == 1.0 == True). */
|
|
237
|
+
export class PyDict {
|
|
238
|
+
constructor() { this.m = new Map(); }
|
|
239
|
+
static keyOf(k) {
|
|
240
|
+
if (k === null) return 'N';
|
|
241
|
+
if (typeof k === 'string') return `s${k}`;
|
|
242
|
+
if (typeof k === 'boolean' || typeof k === 'bigint' || k instanceof Dec) return `n${Dec.of(k).key()}`;
|
|
243
|
+
if (k instanceof Money) return `m${k.amount.key()}`;
|
|
244
|
+
if (k instanceof PyDate) return `d${k.iso()}`;
|
|
245
|
+
if (k instanceof Tuple) return `t(${k.items.map(PyDict.keyOf).join(',')})`;
|
|
246
|
+
if (k === NOT_GIVEN) return 'G';
|
|
247
|
+
throw TypeErr(`unhashable type: '${typeName(k)}'`);
|
|
248
|
+
}
|
|
249
|
+
has(k) { return this.m.has(PyDict.keyOf(k)); }
|
|
250
|
+
get(k) { const e = this.m.get(PyDict.keyOf(k)); return e ? e[1] : undefined; }
|
|
251
|
+
set(k, v) { const id = PyDict.keyOf(k); const e = this.m.get(id); if (e) e[1] = v; else this.m.set(id, [k, v]); }
|
|
252
|
+
delete(k) { this.m.delete(PyDict.keyOf(k)); }
|
|
253
|
+
get size() { return this.m.size; }
|
|
254
|
+
keys() { return [...this.m.values()].map((e) => e[0]); }
|
|
255
|
+
values() { return [...this.m.values()].map((e) => e[1]); }
|
|
256
|
+
items() { return [...this.m.values()].map((e) => new Tuple([e[0], e[1]])); }
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** A record (a Python dataclass): its kind, and its field values in declaration order. */
|
|
260
|
+
export class RecordVal {
|
|
261
|
+
constructor(cls) { this.cls = cls; this.f = new Map(); }
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// ── Kinds ──────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
265
|
+
|
|
266
|
+
export const isInt = (x) => typeof x === 'bigint';
|
|
267
|
+
export const isNumber = (x) => typeof x === 'bigint' || x instanceof Dec; // _is_number: never yes/no
|
|
268
|
+
const isIntLike = (x) => typeof x === 'bigint' || typeof x === 'boolean';
|
|
269
|
+
const isNumLike = (x) => isIntLike(x) || x instanceof Dec; // what Python arithmetic accepts as a number (bool is an int)
|
|
270
|
+
const asBig = (x) => (typeof x === 'boolean' ? (x ? 1n : 0n) : x);
|
|
271
|
+
const numCmp = (a, b) => (isIntLike(a) && isIntLike(b) ? (asBig(a) < asBig(b) ? -1 : asBig(a) > asBig(b) ? 1 : 0) : Dec.cmp(Dec.of(a), Dec.of(b)));
|
|
272
|
+
|
|
273
|
+
/** Python's type name, as its error messages print it. */
|
|
274
|
+
export function typeName(v) {
|
|
275
|
+
if (v === null || v === undefined) return 'NoneType';
|
|
276
|
+
if (typeof v === 'boolean') return 'bool';
|
|
277
|
+
if (typeof v === 'bigint') return 'int';
|
|
278
|
+
if (typeof v === 'string') return 'str';
|
|
279
|
+
if (v instanceof Dec) return 'decimal.Decimal';
|
|
280
|
+
if (v instanceof Money) return 'Money';
|
|
281
|
+
if (Array.isArray(v)) return 'list';
|
|
282
|
+
if (v instanceof Tuple) return 'tuple';
|
|
283
|
+
if (v instanceof PyDict) return 'dict';
|
|
284
|
+
if (v instanceof PyDate) return 'datetime.date';
|
|
285
|
+
if (v instanceof RecordVal) return v.cls.py;
|
|
286
|
+
if (v === NOT_GIVEN) return '_NotGiven';
|
|
287
|
+
if (v && v.isFunc) return 'function';
|
|
288
|
+
return 'object';
|
|
289
|
+
}
|
|
290
|
+
const shortName = (v) => (v instanceof Dec ? 'Decimal' : v instanceof PyDate ? 'date' : typeName(v));
|
|
291
|
+
|
|
292
|
+
/** _describe(v) in thunder_runtime.py. */
|
|
293
|
+
export function describe(v) {
|
|
294
|
+
if (v === null) return 'nothing';
|
|
295
|
+
if (typeof v === 'boolean') return 'a yes/no value';
|
|
296
|
+
if (typeof v === 'string') return `the text "${v}"`;
|
|
297
|
+
if (isNumber(v)) return `the number ${show(v)}`;
|
|
298
|
+
if (v instanceof Money) return v.toString();
|
|
299
|
+
return `a value (${shortName(v)})`;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** show(v): a value the way Thunder says it. */
|
|
303
|
+
export function show(v) {
|
|
304
|
+
if (v === null || v === undefined) return 'nothing';
|
|
305
|
+
if (v === true) return 'yes';
|
|
306
|
+
if (v === false) return 'no';
|
|
307
|
+
if (v instanceof Dec) { const t = v.toFixed(); return t.includes('.') ? t.replace(/0+$/, '').replace(/\.$/, '') : t; }
|
|
308
|
+
if (Array.isArray(v)) return `[${v.map(show).join(', ')}]`;
|
|
309
|
+
if (v instanceof Tuple) return `[${v.items.map(show).join(', ')}]`;
|
|
310
|
+
if (v instanceof PyDict) return `{${[...v.m.values()].map(([k, x]) => `${show(k)}: ${show(x)}`).join(', ')}}`;
|
|
311
|
+
if (v instanceof RecordVal) return `${v.cls.py}(${v.cls.fields.map((f) => `${f.py.replace(/_/g, ' ')}: ${show(v.f.get(f.py))}`).join(', ')})`;
|
|
312
|
+
if (v instanceof PyDate) return v.iso();
|
|
313
|
+
return pyStr(v);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** Python's repr(v). */
|
|
317
|
+
export function pyRepr(v) {
|
|
318
|
+
if (typeof v === 'string') {
|
|
319
|
+
const q = v.includes("'") && !v.includes('"') ? '"' : "'";
|
|
320
|
+
let out = '';
|
|
321
|
+
for (const ch of v) {
|
|
322
|
+
const cp = ch.codePointAt(0);
|
|
323
|
+
if (ch === '\\') out += '\\\\';
|
|
324
|
+
else if (ch === q) out += `\\${q}`;
|
|
325
|
+
else if (ch === '\n') out += '\\n';
|
|
326
|
+
else if (ch === '\r') out += '\\r';
|
|
327
|
+
else if (ch === '\t') out += '\\t';
|
|
328
|
+
else if (cp < 0x20 || cp === 0x7f) out += `\\x${cp.toString(16).padStart(2, '0')}`;
|
|
329
|
+
else out += ch;
|
|
330
|
+
}
|
|
331
|
+
return q + out + q;
|
|
332
|
+
}
|
|
333
|
+
if (v === null) return 'None';
|
|
334
|
+
if (typeof v === 'boolean') return v ? 'True' : 'False';
|
|
335
|
+
if (typeof v === 'bigint') return v.toString();
|
|
336
|
+
if (v instanceof Dec) return `Decimal('${v.toString()}')`;
|
|
337
|
+
if (v instanceof Money) return `Money('${v.amount.toFixed()}')`;
|
|
338
|
+
if (Array.isArray(v)) return `[${v.map(pyRepr).join(', ')}]`;
|
|
339
|
+
if (v instanceof Tuple) return v.items.length === 1 ? `(${pyRepr(v.items[0])},)` : `(${v.items.map(pyRepr).join(', ')})`;
|
|
340
|
+
if (v instanceof PyDict) return `{${[...v.m.values()].map(([k, x]) => `${pyRepr(k)}: ${pyRepr(x)}`).join(', ')}}`;
|
|
341
|
+
if (v instanceof PyDate) return `datetime.date(${v.y}, ${v.m}, ${v.d})`;
|
|
342
|
+
if (v instanceof RecordVal) return `${v.cls.py}(${v.cls.fields.map((f) => `${f.py}=${pyRepr(v.f.get(f.py))}`).join(', ')})`;
|
|
343
|
+
if (v === NOT_GIVEN) return 'not given';
|
|
344
|
+
return String(v);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** Python's str(v). */
|
|
348
|
+
export function pyStr(v) {
|
|
349
|
+
if (typeof v === 'string') return v;
|
|
350
|
+
if (v instanceof Money) return v.toString();
|
|
351
|
+
if (v instanceof PyDate) return v.iso();
|
|
352
|
+
if (v instanceof Dec) return v.toString();
|
|
353
|
+
return pyRepr(v);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** Python's truth value (used only where the generated Python uses it: "where" conditions and Never rules). */
|
|
357
|
+
export function truthy(v) {
|
|
358
|
+
if (v === null || v === false) return false;
|
|
359
|
+
if (v === true) return true;
|
|
360
|
+
if (typeof v === 'bigint') return v !== 0n;
|
|
361
|
+
if (v instanceof Dec) return !v.isZero();
|
|
362
|
+
if (typeof v === 'string') return v.length > 0;
|
|
363
|
+
if (Array.isArray(v)) return v.length > 0;
|
|
364
|
+
if (v instanceof Tuple) return v.items.length > 0;
|
|
365
|
+
if (v instanceof PyDict) return v.size > 0;
|
|
366
|
+
return true;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** yes_no(v): a condition needs a real yes/no value. */
|
|
370
|
+
export function yesNo(v) {
|
|
371
|
+
if (typeof v === 'boolean') return v;
|
|
372
|
+
throw KindMismatch(`This needs a yes/no value, but it is ${describe(v)}. Compare it instead, for example: is 0, is empty, is nothing.`);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** _decimal(x) in thunder_runtime.py. */
|
|
376
|
+
export function toDec(x) {
|
|
377
|
+
if (x instanceof Dec) return x;
|
|
378
|
+
if (typeof x === 'boolean') throw KindMismatch('A yes/no value was used where a number was needed.');
|
|
379
|
+
if (typeof x === 'bigint') return Dec.int(x);
|
|
380
|
+
if (x === null) throw KindMismatch('A value was nothing where a number was needed.');
|
|
381
|
+
throw KindMismatch(`${describe(x)} was used where a number was needed.`);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// ── Python operators ───────────────────────────────────────────────────────────────────────────────────────────
|
|
385
|
+
|
|
386
|
+
const strLen = (s) => { let n = 0; for (const _ of s) n++; return n; };
|
|
387
|
+
|
|
388
|
+
export function pyLen(v) {
|
|
389
|
+
if (typeof v === 'string') return BigInt(strLen(v));
|
|
390
|
+
if (Array.isArray(v)) return BigInt(v.length);
|
|
391
|
+
if (v instanceof Tuple) return BigInt(v.items.length);
|
|
392
|
+
if (v instanceof PyDict) return BigInt(v.size);
|
|
393
|
+
throw TypeErr(`object of type '${typeName(v)}' has no len()`);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** Iterate a value the way Python's for loop does. */
|
|
397
|
+
export function pyIter(v) {
|
|
398
|
+
if (Array.isArray(v)) return v;
|
|
399
|
+
if (v instanceof Tuple) return v.items;
|
|
400
|
+
if (typeof v === 'string') return Array.from(v);
|
|
401
|
+
if (v instanceof PyDict) return v.keys();
|
|
402
|
+
throw TypeErr(`'${typeName(v)}' object is not iterable`);
|
|
403
|
+
}
|
|
404
|
+
export const pyList = (v) => [...pyIter(v)];
|
|
405
|
+
|
|
406
|
+
export function add(a, b) {
|
|
407
|
+
if (a instanceof Money) return new Money(Dec.add(a.amount, moneyOther(b, 'add')));
|
|
408
|
+
if (b instanceof Money) return new Money(Dec.add(b.amount, moneyOther(a, 'add')));
|
|
409
|
+
if (isIntLike(a) && isIntLike(b)) return asBig(a) + asBig(b);
|
|
410
|
+
if (isNumLike(a) && isNumLike(b)) return Dec.add(Dec.of(a), Dec.of(b));
|
|
411
|
+
if (typeof a === 'string') { if (typeof b === 'string') return a + b; throw TypeErr(`can only concatenate str (not "${typeName(b)}") to str`); }
|
|
412
|
+
if (Array.isArray(a)) { if (Array.isArray(b)) return [...a, ...b]; throw TypeErr(`can only concatenate list (not "${typeName(b)}") to list`); }
|
|
413
|
+
if (a instanceof Tuple) { if (b instanceof Tuple) return new Tuple([...a.items, ...b.items]); throw TypeErr(`can only concatenate tuple (not "${typeName(b)}") to tuple`); }
|
|
414
|
+
throw TypeErr(`unsupported operand type(s) for +: '${typeName(a)}' and '${typeName(b)}'`);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
export function sub(a, b) {
|
|
418
|
+
if (a instanceof Money) return new Money(Dec.sub(a.amount, moneyOther(b, 'subtract')));
|
|
419
|
+
if (b instanceof Money) return new Money(Dec.sub(moneyOther(a, 'subtract'), b.amount));
|
|
420
|
+
if (isIntLike(a) && isIntLike(b)) return asBig(a) - asBig(b);
|
|
421
|
+
if (isNumLike(a) && isNumLike(b)) return Dec.sub(Dec.of(a), Dec.of(b));
|
|
422
|
+
throw TypeErr(`unsupported operand type(s) for -: '${typeName(a)}' and '${typeName(b)}'`);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const repeat = (seq, n) => { const k = Number(asBig(n)); if (typeof seq === 'string') return k > 0 ? seq.repeat(k) : ''; const out = []; for (let i = 0; i < k; i++) out.push(...seq); return out; };
|
|
426
|
+
|
|
427
|
+
export function mul(a, b) {
|
|
428
|
+
if (a instanceof Money) { if (b instanceof Money) throw KindMismatch("Money can't be multiplied by money."); return new Money(Dec.mul(a.amount, toDec(b))); }
|
|
429
|
+
if (b instanceof Money) return new Money(Dec.mul(b.amount, toDec(a)));
|
|
430
|
+
if (isIntLike(a) && isIntLike(b)) return asBig(a) * asBig(b);
|
|
431
|
+
if (isNumLike(a) && isNumLike(b)) return Dec.mul(Dec.of(a), Dec.of(b));
|
|
432
|
+
const seq = (x) => typeof x === 'string' || Array.isArray(x);
|
|
433
|
+
if (seq(a)) { if (isIntLike(b)) return repeat(a, b); throw TypeErr(`can't multiply sequence by non-int of type '${typeName(b)}'`); }
|
|
434
|
+
if (seq(b)) { if (isIntLike(a)) return repeat(b, a); throw TypeErr(`can't multiply sequence by non-int of type '${typeName(a)}'`); }
|
|
435
|
+
throw TypeErr(`unsupported operand type(s) for *: '${typeName(a)}' and '${typeName(b)}'`);
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
export function neg(a) {
|
|
439
|
+
if (a instanceof Money) return new Money(a.amount.neg());
|
|
440
|
+
if (isIntLike(a)) return -asBig(a);
|
|
441
|
+
if (a instanceof Dec) return a.neg();
|
|
442
|
+
throw TypeErr(`bad operand type for unary -: '${typeName(a)}'`);
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/** Python's % on two whole numbers: the sign of the divisor. */
|
|
446
|
+
export function intMod(a, b) {
|
|
447
|
+
const x = asBig(a), y = asBig(b);
|
|
448
|
+
if (!isIntLike(a) || !isIntLike(b)) return pyModGeneric(a, b);
|
|
449
|
+
if (y === 0n) throw new PyErr('ZeroDivisionError', 'integer modulo by zero');
|
|
450
|
+
let r = x % y;
|
|
451
|
+
if (r !== 0n && (r < 0n) !== (y < 0n)) r += y;
|
|
452
|
+
return r;
|
|
453
|
+
}
|
|
454
|
+
function pyModGeneric(a, b) {
|
|
455
|
+
if (isNumLike(a) && isNumLike(b)) return modulo(a, b);
|
|
456
|
+
throw TypeErr(`unsupported operand type(s) for %: '${typeName(a)}' and '${typeName(b)}'`);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/** divide(a, b) in thunder_runtime.py: always exact. */
|
|
460
|
+
export function divide(a, b) {
|
|
461
|
+
if (a instanceof Money) {
|
|
462
|
+
if (b instanceof Money) { if (b.amount.isZero()) throw DividedByZero('You divided by zero.'); return Dec.div(a.amount, b.amount); }
|
|
463
|
+
const d = toDec(b);
|
|
464
|
+
if (d.isZero()) throw DividedByZero('You divided by zero.');
|
|
465
|
+
return new Money(Dec.div(a.amount, d));
|
|
466
|
+
}
|
|
467
|
+
if (b instanceof Money) throw KindMismatch("A plain number can't be divided by money.");
|
|
468
|
+
const x = toDec(a), y = toDec(b);
|
|
469
|
+
if (y.isZero()) throw DividedByZero('You divided by zero.');
|
|
470
|
+
return Dec.div(x, y);
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** modulo(a, b) in thunder_runtime.py. */
|
|
474
|
+
export function modulo(a, b) {
|
|
475
|
+
const money = a instanceof Money;
|
|
476
|
+
const x = money ? a.amount : toDec(a);
|
|
477
|
+
const y = b instanceof Money ? b.amount : toDec(b);
|
|
478
|
+
if (y.isZero()) throw DividedByZero('You divided by zero.');
|
|
479
|
+
let r = Dec.rem(x, y);
|
|
480
|
+
if (!r.isZero() && (r.s === 1) !== (y.s === 1 && !y.isZero())) r = Dec.add(r, y);
|
|
481
|
+
if (money) return new Money(r);
|
|
482
|
+
return typeof a === 'bigint' && typeof b === 'bigint' ? r.toBigInt() : r;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/** round_to(x, places). */
|
|
486
|
+
export function roundTo(x, places = 0n) {
|
|
487
|
+
const p = Number(asBig(places instanceof Dec ? places.toBigInt() : places));
|
|
488
|
+
if (x instanceof Money) return new Money(x.amount.quantizeHalfUp(-p));
|
|
489
|
+
if (typeof x === 'bigint') return x;
|
|
490
|
+
const d = toDec(x).quantizeHalfUp(-p);
|
|
491
|
+
return p === 0 ? d.toBigInt() : d;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** Python ==. */
|
|
495
|
+
export function eq(a, b) {
|
|
496
|
+
if (a === b && !(a instanceof Dec)) return true;
|
|
497
|
+
if (a instanceof Money || b instanceof Money) {
|
|
498
|
+
const [m, o] = a instanceof Money ? [a, b] : [b, a];
|
|
499
|
+
if (o === null || typeof o === 'string' || typeof o === 'boolean') return false;
|
|
500
|
+
return Dec.cmp(m.amount, moneyOther(o, 'compare')) === 0;
|
|
501
|
+
}
|
|
502
|
+
if (a === null || b === null) return false;
|
|
503
|
+
if (isNumLike(a) && isNumLike(b)) return numCmp(a, b) === 0;
|
|
504
|
+
if (typeof a === 'string' || typeof b === 'string') return a === b;
|
|
505
|
+
if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((x, i) => x === b[i] || eq(x, b[i]));
|
|
506
|
+
if (a instanceof Tuple && b instanceof Tuple) return a.items.length === b.items.length && a.items.every((x, i) => eq(x, b.items[i]));
|
|
507
|
+
if (a instanceof PyDict && b instanceof PyDict) return a.size === b.size && [...a.m.entries()].every(([k, [, v]]) => b.m.has(k) && eq(v, b.m.get(k)[1]));
|
|
508
|
+
if (a instanceof RecordVal && b instanceof RecordVal) return a.cls === b.cls && a.cls.fields.every((f) => eq(a.f.get(f.py), b.f.get(f.py)));
|
|
509
|
+
if (a instanceof PyDate && b instanceof PyDate) return a.num() === b.num();
|
|
510
|
+
return false;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
const FLIP = { '<': '>', '>': '<', '<=': '>=', '>=': '<=' };
|
|
514
|
+
const holds = (op, c) => (op === '<' ? c < 0 : op === '>' ? c > 0 : op === '<=' ? c <= 0 : c >= 0);
|
|
515
|
+
|
|
516
|
+
/** Python <, >, <=, >= (and == / != through eq). */
|
|
517
|
+
export function compare(op, a, b) {
|
|
518
|
+
if (op === '==') return eq(a, b);
|
|
519
|
+
if (op === '!=') return !eq(a, b);
|
|
520
|
+
if (a instanceof Money || b instanceof Money) {
|
|
521
|
+
const [m, o, o2] = a instanceof Money ? [a, b, op] : [b, a, FLIP[op]];
|
|
522
|
+
if (o === null) throw TypeErr(`'${o2}' not supported between instances of 'decimal.Decimal' and 'NoneType'`);
|
|
523
|
+
return holds(o2, Dec.cmp(m.amount, moneyOther(o, 'compare')));
|
|
524
|
+
}
|
|
525
|
+
const c = order(a, b);
|
|
526
|
+
if (c === null) throw TypeErr(`'${op}' not supported between instances of '${typeName(a)}' and '${typeName(b)}'`);
|
|
527
|
+
return holds(op, c);
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** -1, 0, 1, or null when Python cannot order the two. */
|
|
531
|
+
function order(a, b) {
|
|
532
|
+
if (isNumLike(a) && isNumLike(b)) return numCmp(a, b);
|
|
533
|
+
if (typeof a === 'string' && typeof b === 'string') return cmpStr(a, b);
|
|
534
|
+
if (a instanceof PyDate && b instanceof PyDate) return Math.sign(a.num() - b.num());
|
|
535
|
+
const seqA = Array.isArray(a) ? a : a instanceof Tuple ? a.items : null;
|
|
536
|
+
const seqB = Array.isArray(b) ? b : b instanceof Tuple ? b.items : null;
|
|
537
|
+
if (seqA && seqB && Array.isArray(a) === Array.isArray(b)) {
|
|
538
|
+
for (let i = 0; i < Math.min(seqA.length, seqB.length); i++) {
|
|
539
|
+
if (eq(seqA[i], seqB[i])) continue;
|
|
540
|
+
return compare('<', seqA[i], seqB[i]) ? -1 : 1;
|
|
541
|
+
}
|
|
542
|
+
return Math.sign(seqA.length - seqB.length);
|
|
543
|
+
}
|
|
544
|
+
return null;
|
|
545
|
+
}
|
|
546
|
+
function cmpStr(a, b) {
|
|
547
|
+
const x = Array.from(a), y = Array.from(b);
|
|
548
|
+
for (let i = 0; i < Math.min(x.length, y.length); i++) { const d = x[i].codePointAt(0) - y[i].codePointAt(0); if (d) return Math.sign(d); }
|
|
549
|
+
return Math.sign(x.length - y.length);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/** Python's `item in container`. */
|
|
553
|
+
export function contains(container, item) {
|
|
554
|
+
if (typeof container === 'string') {
|
|
555
|
+
if (typeof item !== 'string') throw TypeErr(`'in <string>' requires string as left operand, not ${typeName(item)}`);
|
|
556
|
+
return container.includes(item);
|
|
557
|
+
}
|
|
558
|
+
if (container instanceof PyDict) return container.has(item);
|
|
559
|
+
if (Array.isArray(container)) return container.some((x) => x === item || eq(x, item));
|
|
560
|
+
if (container instanceof Tuple) return container.items.some((x) => eq(x, item));
|
|
561
|
+
throw TypeErr(`argument of type '${typeName(container)}' is not iterable`);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/** Python's list.sort / sorted: stable, using < only. */
|
|
565
|
+
export function pySort(items, key, reverse) {
|
|
566
|
+
const keyed = items.map((v, i) => ({ v, k: key ? key(v) : v, i }));
|
|
567
|
+
keyed.sort((x, y) => {
|
|
568
|
+
if (compare('<', reverse ? y.k : x.k, reverse ? x.k : y.k)) return -1;
|
|
569
|
+
if (compare('<', reverse ? x.k : y.k, reverse ? y.k : x.k)) return 1;
|
|
570
|
+
return x.i - y.i;
|
|
571
|
+
});
|
|
572
|
+
return keyed.map((x) => x.v);
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
// ── Attribute-style Python calls the generated code makes on values ────────────────────────────────────────────
|
|
576
|
+
|
|
577
|
+
export function attrErr(v, name) { return new PyErr('AttributeError', `'${typeName(v)}' object has no attribute '${name}'`); }
|
|
578
|
+
export function strMethod(v, name) { if (typeof v !== 'string') throw attrErr(v, name); return v; }
|
|
579
|
+
|
|
580
|
+
const SPLITLINES = /\r\n|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029]/;
|
|
581
|
+
export function splitLines(s) {
|
|
582
|
+
const out = [];
|
|
583
|
+
let rest = s;
|
|
584
|
+
while (rest.length) {
|
|
585
|
+
const m = rest.match(SPLITLINES);
|
|
586
|
+
if (!m) { out.push(rest); break; }
|
|
587
|
+
out.push(rest.slice(0, m.index));
|
|
588
|
+
rest = rest.slice(m.index + m[0].length);
|
|
589
|
+
}
|
|
590
|
+
return out;
|
|
591
|
+
}
|
|
592
|
+
const PY_SPACE = /[\s\x1c-\x1f\x85]+/u;
|
|
593
|
+
export const pySplit = (s) => s.split(PY_SPACE).filter((x) => x !== '');
|
|
594
|
+
export const pyStrip = (s) => s.replace(/^[\s\x1c-\x1f\x85]+|[\s\x1c-\x1f\x85]+$/gu, '');
|
|
595
|
+
|
|
596
|
+
// ── JSON, the way Python's json module reads and writes it ─────────────────────────────────────────────────────
|
|
597
|
+
|
|
598
|
+
class JsonError extends Error { constructor(msg, pos) { super(msg); this.pos = pos; } }
|
|
599
|
+
|
|
600
|
+
export function jsonParse(text) {
|
|
601
|
+
const s = text, n = s.length;
|
|
602
|
+
const ws = (i) => { while (i < n && ' \t\n\r'.includes(s[i])) i++; return i; };
|
|
603
|
+
const NUM = /-?(?:0|[1-9]\d*)(\.\d+)?([eE][-+]?\d+)?/y;
|
|
604
|
+
function str(begin) {
|
|
605
|
+
let i = begin + 1, out = '';
|
|
606
|
+
for (;;) {
|
|
607
|
+
if (i >= n) throw new JsonError('Unterminated string starting at', begin);
|
|
608
|
+
const ch = s[i];
|
|
609
|
+
if (ch === '"') return [out, i + 1];
|
|
610
|
+
if (ch.charCodeAt(0) < 0x20) throw new JsonError('Invalid control character at', i);
|
|
611
|
+
if (ch !== '\\') { out += ch; i++; continue; }
|
|
612
|
+
if (i + 1 >= n) throw new JsonError('Unterminated string starting at', begin);
|
|
613
|
+
const esc = s[i + 1];
|
|
614
|
+
const simple = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' }[esc];
|
|
615
|
+
if (simple !== undefined) { out += simple; i += 2; continue; }
|
|
616
|
+
if (esc !== 'u') throw new JsonError('Invalid \\escape', i);
|
|
617
|
+
const hex = s.slice(i + 2, i + 6);
|
|
618
|
+
if (!/^[0-9a-fA-F]{4}$/.test(hex)) throw new JsonError('Invalid \\uXXXX escape', i + 1);
|
|
619
|
+
let cp = parseInt(hex, 16);
|
|
620
|
+
i += 6;
|
|
621
|
+
if (cp >= 0xd800 && cp <= 0xdbff && s[i] === '\\' && s[i + 1] === 'u' && /^[0-9a-fA-F]{4}$/.test(s.slice(i + 2, i + 6))) {
|
|
622
|
+
const lo = parseInt(s.slice(i + 2, i + 6), 16);
|
|
623
|
+
if (lo >= 0xdc00 && lo <= 0xdfff) { cp = 0x10000 + ((cp - 0xd800) << 10) + (lo - 0xdc00); i += 6; }
|
|
624
|
+
}
|
|
625
|
+
out += String.fromCodePoint(cp);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
function value(i) {
|
|
629
|
+
if (i >= n) throw new JsonError('Expecting value', i);
|
|
630
|
+
const ch = s[i];
|
|
631
|
+
if (ch === '"') return str(i);
|
|
632
|
+
if (ch === '{') return obj(i + 1);
|
|
633
|
+
if (ch === '[') return arr(i + 1);
|
|
634
|
+
if (s.startsWith('null', i)) return [null, i + 4];
|
|
635
|
+
if (s.startsWith('true', i)) return [true, i + 4];
|
|
636
|
+
if (s.startsWith('false', i)) return [false, i + 4];
|
|
637
|
+
NUM.lastIndex = i;
|
|
638
|
+
const m = NUM.exec(s);
|
|
639
|
+
if (m) {
|
|
640
|
+
if (m[1] || m[2]) return [Dec.parse(m[0]), i + m[0].length];
|
|
641
|
+
return [BigInt(m[0]), i + m[0].length];
|
|
642
|
+
}
|
|
643
|
+
throw new JsonError('Expecting value', i);
|
|
644
|
+
}
|
|
645
|
+
function obj(i) {
|
|
646
|
+
const d = new PyDict();
|
|
647
|
+
i = ws(i);
|
|
648
|
+
if (s[i] === '}') return [d, i + 1];
|
|
649
|
+
for (;;) {
|
|
650
|
+
if (i >= n || s[i] !== '"') throw new JsonError('Expecting property name enclosed in double quotes', i);
|
|
651
|
+
let k; [k, i] = str(i);
|
|
652
|
+
i = ws(i);
|
|
653
|
+
if (i >= n || s[i] !== ':') throw new JsonError("Expecting ':' delimiter", i);
|
|
654
|
+
i = ws(i + 1);
|
|
655
|
+
let v; [v, i] = value(i);
|
|
656
|
+
d.set(k, v);
|
|
657
|
+
i = ws(i);
|
|
658
|
+
if (i < n && s[i] === '}') return [d, i + 1];
|
|
659
|
+
if (i >= n || s[i] !== ',') throw new JsonError("Expecting ',' delimiter", i);
|
|
660
|
+
const comma = i;
|
|
661
|
+
i = ws(i + 1);
|
|
662
|
+
if (s[i] === '}') throw new JsonError('Illegal trailing comma before end of object', comma);
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
function arr(i) {
|
|
666
|
+
const out = [];
|
|
667
|
+
i = ws(i);
|
|
668
|
+
if (s[i] === ']') return [out, i + 1];
|
|
669
|
+
for (;;) {
|
|
670
|
+
let v; [v, i] = value(i);
|
|
671
|
+
out.push(v);
|
|
672
|
+
i = ws(i);
|
|
673
|
+
if (i < n && s[i] === ']') return [out, i + 1];
|
|
674
|
+
if (i >= n || s[i] !== ',') throw new JsonError("Expecting ',' delimiter", i);
|
|
675
|
+
const comma = i;
|
|
676
|
+
i = ws(i + 1);
|
|
677
|
+
if (s[i] === ']') throw new JsonError('Illegal trailing comma before end of array', comma);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
try {
|
|
681
|
+
let [v, end] = value(ws(0));
|
|
682
|
+
end = ws(end);
|
|
683
|
+
if (end !== n) throw new JsonError('Extra data', end);
|
|
684
|
+
return v;
|
|
685
|
+
} catch (e) {
|
|
686
|
+
if (!(e instanceof JsonError)) throw e;
|
|
687
|
+
const before = s.slice(0, e.pos);
|
|
688
|
+
const line = (before.match(/\n/g) || []).length + 1;
|
|
689
|
+
const col = e.pos - before.lastIndexOf('\n');
|
|
690
|
+
throw ConversionFailed(`This is not JSON: ${e.message} (line ${line}, column ${col}).`);
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
function jsonReady(v) {
|
|
695
|
+
if (v === null || typeof v === 'boolean' || typeof v === 'string' || typeof v === 'bigint' || v instanceof Dec) return v;
|
|
696
|
+
if (v instanceof Money) throw KindMismatch("Money has no JSON form of its own: use its amount, for example price's amount.");
|
|
697
|
+
if (Array.isArray(v)) return v.map(jsonReady);
|
|
698
|
+
if (v instanceof Tuple) return v.items.map(jsonReady);
|
|
699
|
+
if (v instanceof PyDict) {
|
|
700
|
+
const out = new PyDict();
|
|
701
|
+
for (const [k, x] of v.m.values()) { if (typeof k !== 'string') throw KindMismatch(`A JSON object's keys are text, but one is ${describe(k)}.`); out.set(k, jsonReady(x)); }
|
|
702
|
+
return out;
|
|
703
|
+
}
|
|
704
|
+
if (v instanceof RecordVal) { const out = new PyDict(); for (const f of v.cls.fields) out.set(f.py, jsonReady(v.f.get(f.py))); return out; }
|
|
705
|
+
throw KindMismatch(`${describe(v)} has no JSON form.`);
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
const jsonStr = (s) => `"${Array.from(s).map((ch) => {
|
|
709
|
+
const cp = ch.codePointAt(0);
|
|
710
|
+
if (ch === '"') return '\\"';
|
|
711
|
+
if (ch === '\\') return '\\\\';
|
|
712
|
+
if (ch === '\n') return '\\n';
|
|
713
|
+
if (ch === '\r') return '\\r';
|
|
714
|
+
if (ch === '\t') return '\\t';
|
|
715
|
+
if (ch === '\b') return '\\b';
|
|
716
|
+
if (ch === '\f') return '\\f';
|
|
717
|
+
if (cp >= 0x20 && cp <= 0x7e) return ch;
|
|
718
|
+
if (cp > 0xffff) { const v = cp - 0x10000; return `\\u${(0xd800 + (v >> 10)).toString(16)}\\u${(0xdc00 + (v & 0x3ff)).toString(16)}`; }
|
|
719
|
+
return `\\u${cp.toString(16).padStart(4, '0')}`;
|
|
720
|
+
}).join('')}"`;
|
|
721
|
+
|
|
722
|
+
export function jsonText(v) {
|
|
723
|
+
const w = (x) => {
|
|
724
|
+
if (x === null) return 'null';
|
|
725
|
+
if (x === true) return 'true';
|
|
726
|
+
if (x === false) return 'false';
|
|
727
|
+
if (typeof x === 'bigint') return x.toString();
|
|
728
|
+
if (x instanceof Dec) { const t = x.toString(); return x.isIntegral() && t.includes('E') ? x.toFixed() : t; }
|
|
729
|
+
if (typeof x === 'string') return jsonStr(x);
|
|
730
|
+
if (Array.isArray(x)) return `[${x.map(w).join(', ')}]`;
|
|
731
|
+
return `{${[...x.m.values()].map(([k, y]) => `${jsonStr(k)}: ${w(y)}`).join(', ')}}`;
|
|
732
|
+
};
|
|
733
|
+
return w(jsonReady(v));
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
// ── Helpers the generated code calls (moved from the engine so the engine and compiled TypeScript share them) ────
|
|
737
|
+
|
|
738
|
+
export const MAX_FRAMES = 997; // as deep as the generated Python goes (recursion limit 1000, less its own frames)
|
|
739
|
+
|
|
740
|
+
export function rangeInt(v) {
|
|
741
|
+
if (typeof v === 'bigint') return v;
|
|
742
|
+
if (typeof v === 'boolean') return v ? 1n : 0n;
|
|
743
|
+
throw TypeErr(`'${v instanceof Dec ? 'decimal.Decimal' : v === null ? 'NoneType' : v instanceof Money ? 'Money' : typeof v === 'string' ? 'str' : 'object'}' object cannot be interpreted as an integer`);
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
export function unpack2(el) {
|
|
747
|
+
const items = Array.isArray(el) ? el : el instanceof Tuple ? el.items : typeof el === 'string' ? Array.from(el) : el instanceof PyDict ? el.keys() : null;
|
|
748
|
+
if (!items) throw TypeErr(`cannot unpack non-iterable ${el === null ? 'NoneType' : isInt(el) ? 'int' : el instanceof Dec ? 'decimal.Decimal' : typeof el === 'boolean' ? 'bool' : 'object'} object`);
|
|
749
|
+
if (items.length < 2) throw new PyErr('ValueError', `not enough values to unpack (expected 2, got ${items.length})`);
|
|
750
|
+
if (items.length > 2) throw new PyErr('ValueError', `too many values to unpack (expected 2, got ${items.length})`);
|
|
751
|
+
return items;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
export function mapItems(m) { if (!(m instanceof PyDict)) throw attrErr(m, 'items'); return m.items(); }
|
|
755
|
+
export function pairsOf(c) { return c instanceof PyDict ? c.items() : pyList(c); }
|
|
756
|
+
|
|
757
|
+
export function itemAt(items, position, dflt) {
|
|
758
|
+
if (typeof position !== 'bigint') throw KindMismatch(`A position in a list is a whole number, not ${describe(position)}.`);
|
|
759
|
+
const list = Array.isArray(items) ? items : items instanceof Tuple ? items.items : null;
|
|
760
|
+
if (!list) throw TypeErr(`object of type '${items === null ? 'NoneType' : 'object'}' has no len()`);
|
|
761
|
+
if (position >= 1n && position <= BigInt(list.length)) return list[Number(position) - 1];
|
|
762
|
+
if (dflt !== undefined) return dflt;
|
|
763
|
+
throw MissingValue(`There is no item ${position}: the list has ${list.length} item${list.length === 1 ? '' : 's'}.`);
|
|
764
|
+
}
|
|
765
|
+
export function setItem(items, position, value) { itemAt(items, position); items[Number(position) - 1] = value; }
|
|
766
|
+
export function mapSet(m, k, v) {
|
|
767
|
+
if (m instanceof PyDict) { m.set(k, v); return; }
|
|
768
|
+
if (m === null) throw TypeErr("'NoneType' object does not support item assignment");
|
|
769
|
+
if (Array.isArray(m)) { setItem(m, k, v); return; }
|
|
770
|
+
throw TypeErr(`'${m instanceof Money ? 'Money' : 'object'}' object does not support item assignment`);
|
|
771
|
+
}
|
|
772
|
+
export function setEntry(c, k, v) {
|
|
773
|
+
if (Array.isArray(c)) setItem(c, k, v);
|
|
774
|
+
else if (c instanceof PyDict) c.set(k, v);
|
|
775
|
+
else if (c === null) throw MissingValue(`This value is nothing, so it has no entry for ${show(k)}.`);
|
|
776
|
+
else throw KindMismatch(`${describe(c)} has no entries that can be changed.`);
|
|
777
|
+
}
|
|
778
|
+
export function entry(c, k, dflt) {
|
|
779
|
+
if (Array.isArray(c) || c instanceof Tuple) return itemAt(c, k, dflt);
|
|
780
|
+
if (c instanceof PyDict) { if (c.has(k)) return c.get(k); if (dflt !== undefined) return dflt; throw MissingValue(`There is no entry for ${show(k)}.`); }
|
|
781
|
+
if (c === null) throw MissingValue(`This value is nothing, so it has no entry for ${show(k)}.`);
|
|
782
|
+
throw KindMismatch(`${describe(c)} has no entries.`);
|
|
783
|
+
}
|
|
784
|
+
export function mapGet(m, k, dflt) {
|
|
785
|
+
if (m instanceof PyDict) { if (m.has(k)) return m.get(k); if (dflt !== undefined) return dflt; throw new PyErr('KeyError', pyStr(k), [k]); }
|
|
786
|
+
if (m === null) throw dflt !== undefined ? attrErr(m, 'get') : TypeErr("'NoneType' object is not subscriptable");
|
|
787
|
+
if (dflt !== undefined) throw attrErr(m, 'get');
|
|
788
|
+
if (Array.isArray(m)) { const i = Number(k); if (typeof k === 'bigint' && i >= -m.length && i < m.length) return m.at(i); throw new PyErr('IndexError', 'list index out of range'); }
|
|
789
|
+
throw TypeErr(`'${m instanceof Money ? 'Money' : 'object'}' object is not subscriptable`);
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
/** obj.name for a record field (a Python attribute), or Money's amount. */
|
|
793
|
+
export function getAttr(obj, name) {
|
|
794
|
+
if (obj instanceof RecordVal && obj.f.has(name)) return obj.f.get(name);
|
|
795
|
+
if (obj instanceof Money && name === 'amount') return obj.amount;
|
|
796
|
+
throw attrErr(obj, name);
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/** obj.name = value. `checkRules(obj, name, value)` runs the record's Never rules first, as its __setattr__ does. */
|
|
800
|
+
export function setAttrWith(checkRules, obj, name, value) {
|
|
801
|
+
if (obj instanceof RecordVal) { checkRules(obj, name, value); obj.f.set(name, value); return; }
|
|
802
|
+
if (obj instanceof Money) throw new PyErr('AttributeError', 'Money cannot be changed; make new money instead.');
|
|
803
|
+
throw attrErr(obj, name);
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
export function getField(obj, key) {
|
|
807
|
+
if (obj === null) throw MissingValue(`This value is nothing, so it has no ${key}.`);
|
|
808
|
+
const names = [key, key.replace(/ /g, '_'), key.toLowerCase(), key.toLowerCase().replace(/ /g, '_')];
|
|
809
|
+
if (obj instanceof PyDict) {
|
|
810
|
+
for (const k of names) if (obj.has(k)) return obj.get(k);
|
|
811
|
+
for (const [k, v] of obj.m.values()) if (pyStrip(pyStr(k)).toLowerCase() === key.toLowerCase()) return v;
|
|
812
|
+
throw MissingValue(`There is no field "${key}". Fields here: ${obj.keys().map(pyStr).join(', ')}.`);
|
|
813
|
+
}
|
|
814
|
+
for (const k of names) {
|
|
815
|
+
if (obj instanceof RecordVal && obj.f.has(k)) return obj.f.get(k);
|
|
816
|
+
if (obj instanceof Money && k === 'amount') return obj.amount;
|
|
817
|
+
}
|
|
818
|
+
throw MissingValue(`${describe(obj)} has no field "${key}".`);
|
|
819
|
+
}
|
|
820
|
+
export function setFieldWith(setAttr, obj, key, value) {
|
|
821
|
+
if (obj instanceof PyDict) { obj.set(key, value); return; }
|
|
822
|
+
const names = [key, key.replace(/ /g, '_'), key.toLowerCase(), key.toLowerCase().replace(/ /g, '_')];
|
|
823
|
+
for (const k of names) if (obj instanceof RecordVal && obj.f.has(k)) { setAttr(obj, k, value); return; }
|
|
824
|
+
throw MissingValue(`${describe(obj)} has no field "${key}".`);
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
export function addTo(target, value) { if (Array.isArray(target)) { target.push(value); return target; } return add(target, value); }
|
|
828
|
+
export function appendTo(target, value) { if (!Array.isArray(target)) throw attrErr(target, 'append'); target.push(value); }
|
|
829
|
+
export function removeFrom(target, value) {
|
|
830
|
+
if (target instanceof PyDict) { if (!target.has(value)) throw MissingValue(`There is no entry for ${show(value)} to remove.`); target.delete(value); return; }
|
|
831
|
+
if (!contains(target, value)) throw MissingValue(`${show(value)} is not in the list, so it can't be removed.`);
|
|
832
|
+
if (!Array.isArray(target)) throw attrErr(target, 'remove');
|
|
833
|
+
target.splice(target.findIndex((x) => x === value || eq(x, value)), 1);
|
|
834
|
+
}
|
|
835
|
+
export function sortInPlace(target, key, desc) {
|
|
836
|
+
if (!Array.isArray(target)) throw attrErr(target, 'sort');
|
|
837
|
+
const sorted = pySort(target, key, !!desc);
|
|
838
|
+
target.splice(0, target.length, ...sorted);
|
|
839
|
+
}
|
|
840
|
+
export function reverseInPlace(target) { if (!Array.isArray(target)) throw attrErr(target, 'reverse'); target.reverse(); }
|
|
841
|
+
|
|
842
|
+
/** A record: the fields it is given (a Map), the others defaulted; each set through `setAttr` (its Never rules). */
|
|
843
|
+
export function newRecordWith(setAttr, cls, given) {
|
|
844
|
+
const rec = new RecordVal(cls);
|
|
845
|
+
const missing = cls.fields.filter((f) => !given.has(f.py) && !['optional', 'list', 'map'].includes(f.type?.k));
|
|
846
|
+
if (missing.length) throw TypeErr(`${cls.py}.__init__() missing ${missing.length} required keyword-only argument${missing.length === 1 ? '' : 's'}: ${missing.map((f) => `'${f.py}'`).join(missing.length === 2 ? ' and ' : ', ')}`);
|
|
847
|
+
for (const f of cls.fields) {
|
|
848
|
+
const v = given.has(f.py) ? given.get(f.py) : f.type.k === 'optional' ? null : f.type.k === 'list' ? [] : new PyDict();
|
|
849
|
+
setAttr(rec, f.py, v);
|
|
850
|
+
}
|
|
851
|
+
return rec;
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
/** never(cond, text, rule, value): a broken Never rule stops the program. */
|
|
855
|
+
export function never(cond, text, line, value) {
|
|
856
|
+
if (truthy(cond)) throw RuleBroken(`${text} (the rule on line ${line}), but the value is ${show(value)}.`);
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
/** The operations written as words: the sum of, the first of, the words of, … */
|
|
860
|
+
export function applyOp(op, a) {
|
|
861
|
+
switch (op) {
|
|
862
|
+
case 'sum': return totalOf(pyList(a));
|
|
863
|
+
case 'average': { const items = pyList(a); if (!items.length) throw MissingValue("I can't take the average of an empty list."); return divide(totalOf(items), BigInt(items.length)); }
|
|
864
|
+
case 'count': case 'length': return pyLen(a);
|
|
865
|
+
case 'min': { const items = pyList(a); if (!items.length) throw MissingValue('An empty list has no smallest item.'); return items.reduce((best, x) => (compare('<', x, best) ? x : best)); }
|
|
866
|
+
case 'max': { const items = pyList(a); if (!items.length) throw MissingValue('An empty list has no largest item.'); return items.reduce((best, x) => (compare('>', x, best) ? x : best)); }
|
|
867
|
+
case 'first': { const items = pyList(a); if (!items.length) throw MissingValue('An empty list has no first item.'); return items[0]; }
|
|
868
|
+
case 'last': { const items = pyList(a); if (!items.length) throw MissingValue('An empty list has no last item.'); return items[items.length - 1]; }
|
|
869
|
+
case 'words': return pySplit(pyStr(a)).map((p) => stripPunct(p)).filter(Boolean);
|
|
870
|
+
case 'lines': return splitLines(strMethod(a, 'splitlines'));
|
|
871
|
+
case 'lowercase': return strMethod(a, 'lower').toLowerCase();
|
|
872
|
+
case 'uppercase': return strMethod(a, 'upper').toUpperCase();
|
|
873
|
+
case 'trimmed': return pyStrip(strMethod(a, 'strip'));
|
|
874
|
+
case 'parts': return pySplit(textOf(a, '"the parts of"'));
|
|
875
|
+
case 'abs': {
|
|
876
|
+
if (a instanceof Money) return new Money(a.amount.abs());
|
|
877
|
+
if (typeof a === 'boolean' || !(isNumber(a))) throw KindMismatch(`"the absolute value of" needs a number or money, but it is ${describe(a)}.`);
|
|
878
|
+
return typeof a === 'bigint' ? (a < 0n ? -a : a) : a.abs();
|
|
879
|
+
}
|
|
880
|
+
case 'jsonText': return jsonText(a);
|
|
881
|
+
case 'jsonData': return jsonParse(textOf(a, '"the JSON data in"'));
|
|
882
|
+
case 'keys': if (!(a instanceof PyDict)) throw attrErr(a, 'keys'); return a.keys();
|
|
883
|
+
case 'values': if (!(a instanceof PyDict)) throw attrErr(a, 'values'); return a.values();
|
|
884
|
+
default: throw new PyErr('NameError', `name '${op}' is not defined`);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
/** "starts with" / "ends with": both sides must be text. */
|
|
889
|
+
export function affix(t, a, end) {
|
|
890
|
+
const what = end ? '"ends with"' : '"starts with"';
|
|
891
|
+
textOf(t, what); textOf(a, what);
|
|
892
|
+
return end ? t.endsWith(a) : t.startsWith(a);
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
/** a <= v <= hi, the way Python chains it: hi is worked out only when the first part holds. */
|
|
896
|
+
export function between(lo, v, hi) { if (!compare('<=', lo, v)) return false; return compare('<=', v, hi()); }
|
|
897
|
+
/** `item in container`, with the item worked out first (as Python does). */
|
|
898
|
+
export function isIn(item, container) { return contains(container, item); }
|
|
899
|
+
|
|
900
|
+
/** Read a file the program names. `readText(path, cwd)` gives its text or throws with .code 'ENOENT' / 'EISDIR';
|
|
901
|
+
* without one (a browser) every file is missing. */
|
|
902
|
+
export function readTextVia(readText, cwd, path) {
|
|
903
|
+
if (typeof path !== 'string') throw TypeErr(`expected str, bytes or os.PathLike object, not ${path === null ? 'NoneType' : 'object'}`);
|
|
904
|
+
try {
|
|
905
|
+
if (!readText) throw Object.assign(new Error('no files here'), { code: 'ENOENT' });
|
|
906
|
+
return readText(path, cwd);
|
|
907
|
+
}
|
|
908
|
+
catch (err) {
|
|
909
|
+
if (err.code === 'ENOENT') throw MissingValue(`There is no file "${path}" (looked in the folder the program runs in).`);
|
|
910
|
+
throw new PyErr(err.code === 'EISDIR' ? 'IsADirectoryError' : 'OSError', err.message);
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
/** Expect: the checks, the way thunder_runtime.py's expect_* do them. */
|
|
915
|
+
export function expectTrue(v, text) { if (v !== true) throw ExpectationFailed(`${text}, but it was not true.`); }
|
|
916
|
+
export function expectFailure(run, text, msg) {
|
|
917
|
+
try { run(); }
|
|
918
|
+
catch (e) {
|
|
919
|
+
const err = asPyErr(e);
|
|
920
|
+
if (err.thunder && msg !== null) {
|
|
921
|
+
if (typeof msg !== 'string') throw TypeErr(`'in <string>' requires string as left operand, not ${typeof msg === 'bigint' ? 'int' : 'object'}`);
|
|
922
|
+
if (!err.message.includes(msg)) throw ExpectationFailed(`${text}, but it failed with "${err.message}".`);
|
|
923
|
+
}
|
|
924
|
+
return;
|
|
925
|
+
}
|
|
926
|
+
throw ExpectationFailed(`${text}, but it did not fail.`);
|
|
927
|
+
}
|
|
928
|
+
export function expectValue(actual, full, op, want, text) {
|
|
929
|
+
const known = CHECKS[full];
|
|
930
|
+
const ok = known ? known(actual, want) : !CHECKS[op](actual, want);
|
|
931
|
+
if (!ok) throw ExpectationFailed(`${text}, but it was ${show(actual)}.`);
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
/** describe_error(error) in thunder_runtime.py: "main.thunder, line 3 (reached from line 7): … [TC501]". */
|
|
935
|
+
export function describeError(e) {
|
|
936
|
+
const where = e.where ?? [];
|
|
937
|
+
const inner = where[where.length - 1];
|
|
938
|
+
let message = explain(e);
|
|
939
|
+
let code = codeOf(e);
|
|
940
|
+
if (code === 'TC508' && !e.thunder) { message = `Python code used by this line failed: ${message}`; code = 'TC508'; }
|
|
941
|
+
let place = inner ? `${inner.file}, line ${inner.line}` : 'In the program';
|
|
942
|
+
const callers = where.slice(0, -1).map((f) => f.line);
|
|
943
|
+
if (callers.length && inner) place += ` (reached from line ${callers.reverse().join(', then line ')})`;
|
|
944
|
+
return `${place}: ${message} [${code}]`;
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
/** Values the generated code writes literally. */
|
|
948
|
+
export const dec = (text) => Dec.parse(text);
|
|
949
|
+
export const money = (text) => Money.of(text);
|
|
950
|
+
export const today = () => PyDate.today();
|
|
951
|
+
export function date(text) { const d = PyDate.parse(text); if (!d) throw new PyErr('ValueError', `Invalid isoformat string: '${text}'`); return d; }
|
|
952
|
+
export const newMap = () => new PyDict();
|
|
953
|
+
|
|
954
|
+
// ── conversions and text helpers (thunder_runtime.py) ──────────────────────────────────────────────────────────
|
|
955
|
+
|
|
956
|
+
export const CHECKS = {
|
|
957
|
+
is: (a, b) => eq(a, b),
|
|
958
|
+
'is not': (a, b) => !eq(a, b),
|
|
959
|
+
'at least': (a, b) => compare('>=', a, b),
|
|
960
|
+
'at most': (a, b) => compare('<=', a, b),
|
|
961
|
+
'more than': (a, b) => compare('>', a, b),
|
|
962
|
+
'less than': (a, b) => compare('<', a, b),
|
|
963
|
+
nothing: (a) => a === null,
|
|
964
|
+
'not nothing': (a) => a !== null,
|
|
965
|
+
empty: (a) => eq(pyLen(a), 0n),
|
|
966
|
+
positive: (a) => compare('>', a, 0n),
|
|
967
|
+
negative: (a) => compare('<', a, 0n),
|
|
968
|
+
zero: (a) => eq(a, 0n),
|
|
969
|
+
between: (a, b) => compare('<=', b[0], a) && compare('<=', a, b[1]),
|
|
970
|
+
in: (a, b) => contains(b, a),
|
|
971
|
+
contains: (a, b) => contains(a, b),
|
|
972
|
+
};
|
|
973
|
+
|
|
974
|
+
|
|
975
|
+
const NUMBER = /^[+-]?(\d[\d_]*)(\.\d+)?$/;
|
|
976
|
+
|
|
977
|
+
export function toNumber(x) {
|
|
978
|
+
if (isNumber(x)) return x;
|
|
979
|
+
if (x instanceof Money) return x.amount;
|
|
980
|
+
if (typeof x === 'string') {
|
|
981
|
+
const s = pyStrip(x).replace(/,/g, '');
|
|
982
|
+
if (NUMBER.test(s)) return s.includes('.') ? Dec.parse(s) : BigInt(s.replace(/_/g, ''));
|
|
983
|
+
}
|
|
984
|
+
throw ConversionFailed(`${describe(x)} is not a number.`);
|
|
985
|
+
}
|
|
986
|
+
export function toWhole(x) {
|
|
987
|
+
const n = toNumber(x);
|
|
988
|
+
if (typeof n === 'bigint') return n;
|
|
989
|
+
if (n.isIntegral()) return n.toBigInt();
|
|
990
|
+
throw ConversionFailed(`${show(n)} is not a whole number.`);
|
|
991
|
+
}
|
|
992
|
+
export function toMoney(x) {
|
|
993
|
+
if (x instanceof Money) return x;
|
|
994
|
+
if (typeof x === 'string') {
|
|
995
|
+
let s = pyStrip(x).replace(/,/g, '');
|
|
996
|
+
const negative = s.startsWith('-');
|
|
997
|
+
s = s.replace(/^-+/, '').replace(/^\$+/, '');
|
|
998
|
+
if (NUMBER.test(s)) return Money.of((negative ? '-' : '') + s);
|
|
999
|
+
throw ConversionFailed(`${describe(x)} is not an amount of money.`);
|
|
1000
|
+
}
|
|
1001
|
+
return new Money(toDec(toNumber(x)));
|
|
1002
|
+
}
|
|
1003
|
+
export function toYesNo(x) {
|
|
1004
|
+
if (typeof x === 'boolean') return x;
|
|
1005
|
+
if (typeof x === 'string' && ['yes', 'true'].includes(pyStrip(x).toLowerCase())) return true;
|
|
1006
|
+
if (typeof x === 'string' && ['no', 'false'].includes(pyStrip(x).toLowerCase())) return false;
|
|
1007
|
+
throw ConversionFailed(`${describe(x)} is not yes or no.`);
|
|
1008
|
+
}
|
|
1009
|
+
export function toDate(x) {
|
|
1010
|
+
if (x instanceof PyDate) return x;
|
|
1011
|
+
const d = PyDate.parse(pyStrip(pyStr(x)));
|
|
1012
|
+
if (d) return d;
|
|
1013
|
+
throw ConversionFailed(`${describe(x)} is not a date (write it as YYYY-MM-DD).`);
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
export function totalOf(items) {
|
|
1017
|
+
if (!items.length) return 0n;
|
|
1018
|
+
let result = items[0];
|
|
1019
|
+
for (const x of items.slice(1)) result = add(result, x);
|
|
1020
|
+
return result;
|
|
1021
|
+
}
|
|
1022
|
+
export function textOf(v, what) {
|
|
1023
|
+
if (typeof v !== 'string') throw KindMismatch(`${what} needs text, but it is ${describe(v)}.`);
|
|
1024
|
+
return v;
|
|
1025
|
+
}
|
|
1026
|
+
export function joined(items, sep) {
|
|
1027
|
+
sep = textOf(sep, '"joined with"');
|
|
1028
|
+
const out = [];
|
|
1029
|
+
pyIter(items).forEach((x, i) => {
|
|
1030
|
+
if (typeof x !== 'string') throw KindMismatch(`"joined with" joins text, but item ${i + 1} is ${describe(x)}. Turn it into text first.`);
|
|
1031
|
+
out.push(x);
|
|
1032
|
+
});
|
|
1033
|
+
return out.join(sep);
|
|
1034
|
+
}
|
|
1035
|
+
export function splitAt(text, sep) {
|
|
1036
|
+
sep = textOf(sep, '"split at"');
|
|
1037
|
+
if (sep === '') throw KindMismatch('"split at" needs something to split at, not empty text.');
|
|
1038
|
+
return textOf(text, '"split at"').split(sep);
|
|
1039
|
+
}
|
|
1040
|
+
export function replacing(text, old, nw) {
|
|
1041
|
+
old = textOf(old, '"replacing"');
|
|
1042
|
+
if (old === '') throw KindMismatch('"replacing" needs something to replace, not empty text.');
|
|
1043
|
+
const t = textOf(text, '"replacing"');
|
|
1044
|
+
return t.split(old).join(textOf(nw, '"replacing … with"'));
|
|
1045
|
+
}
|
|
1046
|
+
const PUNCT = new Set(Array.from(".,;:!?\"'()[]{}<>“”‘’…-"));
|
|
1047
|
+
export function stripPunct(w) {
|
|
1048
|
+
const a = Array.from(w);
|
|
1049
|
+
let i = 0, j = a.length;
|
|
1050
|
+
while (i < j && PUNCT.has(a[i])) i++;
|
|
1051
|
+
while (j > i && PUNCT.has(a[j - 1])) j--;
|
|
1052
|
+
return a.slice(i, j).join('');
|
|
1053
|
+
}
|
|
1054
|
+
|