@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,3038 @@
1
+ // thunder_runtime.go: written by the Thunder compiler next to compiled Go. Standard library only.
2
+ //
3
+ // The values and rules here are the Thunder engine's own (compiler/src/core/engine-values.mjs), ported to Go, so
4
+ // compiled Go, the Thunder engine, compiled TypeScript, and compiled Python say the same thing for the same program.
5
+ // The compiler's conformance tests run every Core test program on all four and require the same output.
6
+ //
7
+ // Values: whole number -> *big.Int decimal number -> *Dec (exact, like Python's Decimal)
8
+ // money -> *Money text -> string yes/no -> bool nothing -> nil
9
+ // list -> *List (a pair from a map is a *Tuple) map -> *Dict
10
+ // record -> *Record date -> *Date
11
+ package thunder
12
+
13
+ import (
14
+ "bufio"
15
+ "fmt"
16
+ "math/big"
17
+ "os"
18
+ "path/filepath"
19
+ "regexp"
20
+ "strconv"
21
+ "strings"
22
+ "time"
23
+ "unicode"
24
+ "unicode/utf8"
25
+ )
26
+
27
+ // V is any Thunder value.
28
+ type V = interface{}
29
+
30
+ // ── Errors ─────────────────────────────────────────────────────────────────────────────────────────────────────
31
+
32
+ // Place is one frame of where an error happened: the Thunder file and line.
33
+ type Place struct {
34
+ File string
35
+ Line int
36
+ }
37
+
38
+ // Err is a Thunder error (Thunder: true, code TC5xx) or an error Python itself raises (PyType, Python's message).
39
+ type Err struct {
40
+ Thunder bool
41
+ Code string
42
+ PyType string
43
+ Message string
44
+ Args []V
45
+ Where []Place
46
+ HasArgs bool
47
+ }
48
+
49
+ func (e *Err) Error() string { return e.Message }
50
+
51
+ func thunderErr(code, msg, pyType string) *Err {
52
+ return &Err{Thunder: true, Code: code, PyType: pyType, Message: msg}
53
+ }
54
+
55
+ // Stop is "Stop with": TC507.
56
+ func Stop(m V) *Err { return thunderErr("TC507", m.(string), "Stop") }
57
+ func RuleBroken(m string) *Err { return thunderErr("TC504", m, "RuleBroken") }
58
+ func ExpectationFailed(m string) *Err { return thunderErr("TC505", m, "ExpectationFailed") }
59
+ func KindMismatch(m string) *Err { return thunderErr("TC506", m, "TypeError") }
60
+ func ConversionFailed(m string) *Err { return thunderErr("TC509", m, "ValueError") }
61
+ func MissingValue(m string) *Err { return thunderErr("TC503", m, "LookupError") }
62
+ func DividedByZero(m string) *Err { return thunderErr("TC501", m, "ZeroDivisionError") }
63
+
64
+ // PyErr is an error Python raises, with Python's message.
65
+ func PyErr(pyType, m string) *Err { return &Err{PyType: pyType, Message: m} }
66
+ func TypeErr(m string) *Err { return PyErr("TypeError", m) }
67
+
68
+ // Explain is explain(error) in thunder_runtime.py: the error as a sentence.
69
+ func Explain(e *Err) string {
70
+ if e.Thunder {
71
+ return e.Message
72
+ }
73
+ t := e.PyType
74
+ switch {
75
+ case t == "ZeroDivisionError" || t == "DivisionByZero":
76
+ return "You divided by zero."
77
+ case t == "InvalidOperation":
78
+ return "This calculation has no answer (for example, zero divided by zero)."
79
+ case t == "KeyError":
80
+ var a V
81
+ if len(e.Args) > 0 {
82
+ a = e.Args[0]
83
+ }
84
+ return "There is no entry for " + Show(a) + "."
85
+ case (t == "TypeError" || t == "AttributeError") && strings.Contains(e.Message, "NoneType"):
86
+ return "A value was nothing where a value was needed."
87
+ case t == "TypeError":
88
+ return "Values of different kinds were mixed (" + e.Message + ")."
89
+ case t == "RecursionError":
90
+ return "A function called itself too many times."
91
+ }
92
+ return t + ": " + e.Message
93
+ }
94
+
95
+ func codeOf(e *Err) string {
96
+ if e.Thunder {
97
+ return e.Code
98
+ }
99
+ t := e.PyType
100
+ switch {
101
+ case t == "ZeroDivisionError" || t == "DivisionByZero":
102
+ return "TC501"
103
+ case (t == "TypeError" || t == "AttributeError") && strings.Contains(e.Message, "NoneType"):
104
+ return "TC502"
105
+ case t == "KeyError":
106
+ return "TC503"
107
+ case t == "TypeError":
108
+ return "TC506"
109
+ }
110
+ return "TC508"
111
+ }
112
+
113
+ // AsPyErr gives back a Thunder or Python error; anything else (a bug) goes on as it was.
114
+ func AsPyErr(r V) *Err {
115
+ if e, ok := r.(*Err); ok {
116
+ return e
117
+ }
118
+ panic(r)
119
+ }
120
+
121
+ // ── Exact decimals: Python's Decimal with its default context (28 digits, half-even when a result is too long) ──
122
+
123
+ const prec = 28
124
+
125
+ var (
126
+ bigZero = big.NewInt(0)
127
+ bigOne = big.NewInt(1)
128
+ bigTwo = big.NewInt(2)
129
+ bigFive = big.NewInt(5)
130
+ bigTen = big.NewInt(10)
131
+ )
132
+
133
+ func pow10(n int) *big.Int {
134
+ if n <= 0 {
135
+ return big.NewInt(1)
136
+ }
137
+ return new(big.Int).Exp(bigTen, big.NewInt(int64(n)), nil)
138
+ }
139
+ func ndigits(c *big.Int) int {
140
+ if c.Sign() == 0 {
141
+ return 1
142
+ }
143
+ return len(c.String())
144
+ }
145
+
146
+ // Dec is an exact decimal: sign (0 or 1), coefficient >= 0, exponent.
147
+ type Dec struct {
148
+ S int
149
+ C *big.Int
150
+ E int
151
+ }
152
+
153
+ func decInt(n *big.Int) *Dec {
154
+ if n.Sign() < 0 {
155
+ return &Dec{1, new(big.Int).Neg(n), 0}
156
+ }
157
+ return &Dec{0, new(big.Int).Set(n), 0}
158
+ }
159
+
160
+ func decOf(x V) *Dec {
161
+ switch v := x.(type) {
162
+ case *Dec:
163
+ return v
164
+ case *big.Int:
165
+ return decInt(v)
166
+ case bool:
167
+ if v {
168
+ return decInt(bigOne)
169
+ }
170
+ return decInt(bigZero)
171
+ }
172
+ return nil
173
+ }
174
+
175
+ // ParseDec is Decimal("text"): exact; nil when the text is not a number.
176
+ func ParseDec(text string) *Dec {
177
+ s := strings.ReplaceAll(strings.TrimSpace(text), "_", "")
178
+ sign := 0
179
+ if strings.HasPrefix(s, "+") || strings.HasPrefix(s, "-") {
180
+ if s[0] == '-' {
181
+ sign = 1
182
+ }
183
+ s = s[1:]
184
+ }
185
+ exp := 0
186
+ if k := strings.IndexAny(s, "eE"); k >= 0 {
187
+ ev, err := strconv.Atoi(s[k+1:])
188
+ if err != nil || s[k+1:] == "" {
189
+ return nil
190
+ }
191
+ exp = ev
192
+ s = s[:k]
193
+ }
194
+ ip, fp := s, ""
195
+ if k := strings.IndexByte(s, '.'); k >= 0 {
196
+ ip, fp = s[:k], s[k+1:]
197
+ }
198
+ if ip == "" && fp == "" {
199
+ return nil
200
+ }
201
+ for _, ch := range ip + fp {
202
+ if ch < '0' || ch > '9' {
203
+ return nil
204
+ }
205
+ }
206
+ digits := ip + fp
207
+ if digits == "" {
208
+ digits = "0"
209
+ }
210
+ c, _ := new(big.Int).SetString(digits, 10)
211
+ return &Dec{sign, c, exp - len(fp)}
212
+ }
213
+
214
+ func (d *Dec) isZero() bool { return d.C.Sign() == 0 }
215
+
216
+ func (d *Dec) fix() *Dec {
217
+ n := ndigits(d.C) - prec
218
+ if n <= 0 {
219
+ return d
220
+ }
221
+ p := pow10(n)
222
+ q, r := new(big.Int).QuoRem(d.C, p, new(big.Int))
223
+ half := new(big.Int).Mul(bigFive, pow10(n-1))
224
+ c := r.Cmp(half)
225
+ if c > 0 || (c == 0 && q.Bit(0) == 1) {
226
+ q.Add(q, bigOne)
227
+ }
228
+ e := d.E + n
229
+ if ndigits(q) > prec {
230
+ q.Quo(q, bigTen)
231
+ e++
232
+ }
233
+ return &Dec{d.S, q, e}
234
+ }
235
+
236
+ func (d *Dec) signed() *big.Int {
237
+ if d.S == 1 {
238
+ return new(big.Int).Neg(d.C)
239
+ }
240
+ return new(big.Int).Set(d.C)
241
+ }
242
+
243
+ func minInt(a, b int) int {
244
+ if a < b {
245
+ return a
246
+ }
247
+ return b
248
+ }
249
+
250
+ func decAdd(a, b *Dec) *Dec {
251
+ e := minInt(a.E, b.E)
252
+ x := new(big.Int).Mul(a.signed(), pow10(a.E-e))
253
+ y := new(big.Int).Mul(b.signed(), pow10(b.E-e))
254
+ sum := new(big.Int).Add(x, y)
255
+ var s int
256
+ if sum.Sign() == 0 {
257
+ if a.S == 1 && b.S == 1 && a.C.Sign() == 0 && b.C.Sign() == 0 {
258
+ s = 1
259
+ } else if a.C.Sign() == 0 && b.C.Sign() == 0 {
260
+ s = minInt(a.S, b.S)
261
+ } else {
262
+ s = 0
263
+ }
264
+ } else if sum.Sign() < 0 {
265
+ s = 1
266
+ }
267
+ return (&Dec{s, new(big.Int).Abs(sum), e}).fix()
268
+ }
269
+ func (d *Dec) negated() *Dec { return &Dec{1 - d.S, d.C, d.E} }
270
+ func decSub(a, b *Dec) *Dec { return decAdd(a, b.negated()) }
271
+ func decMul(a, b *Dec) *Dec {
272
+ return (&Dec{a.S ^ b.S, new(big.Int).Mul(a.C, b.C), a.E + b.E}).fix()
273
+ }
274
+
275
+ func decDiv(a, b *Dec) *Dec {
276
+ s := a.S ^ b.S
277
+ if a.C.Sign() == 0 {
278
+ return (&Dec{s, big.NewInt(0), a.E - b.E}).fix()
279
+ }
280
+ shift := ndigits(b.C) - ndigits(a.C) + prec + 1
281
+ exp := a.E - b.E - shift
282
+ var coeff, rem *big.Int
283
+ if shift >= 0 {
284
+ n := new(big.Int).Mul(a.C, pow10(shift))
285
+ coeff, rem = new(big.Int).QuoRem(n, b.C, new(big.Int))
286
+ } else {
287
+ dd := new(big.Int).Mul(b.C, pow10(-shift))
288
+ coeff, rem = new(big.Int).QuoRem(a.C, dd, new(big.Int))
289
+ }
290
+ if rem.Sign() != 0 {
291
+ if new(big.Int).Rem(coeff, bigFive).Sign() == 0 {
292
+ coeff.Add(coeff, bigOne)
293
+ }
294
+ } else {
295
+ ideal := a.E - b.E
296
+ for exp < ideal && new(big.Int).Rem(coeff, bigTen).Sign() == 0 {
297
+ coeff.Quo(coeff, bigTen)
298
+ exp++
299
+ }
300
+ }
301
+ return (&Dec{s, coeff, exp}).fix()
302
+ }
303
+
304
+ func decRem(a, b *Dec) *Dec {
305
+ e := minInt(a.E, b.E)
306
+ x := new(big.Int).Mul(a.C, pow10(a.E-e))
307
+ y := new(big.Int).Mul(b.C, pow10(b.E-e))
308
+ return (&Dec{a.S, new(big.Int).Rem(x, y), e}).fix()
309
+ }
310
+
311
+ func (d *Dec) neg() *Dec {
312
+ if d.C.Sign() == 0 {
313
+ return (&Dec{0, big.NewInt(0), d.E}).fix()
314
+ }
315
+ return d.negated().fix()
316
+ }
317
+ func (d *Dec) abs() *Dec { return (&Dec{0, d.C, d.E}).fix() }
318
+
319
+ func decCmp(a, b *Dec) int {
320
+ e := minInt(a.E, b.E)
321
+ x := new(big.Int).Mul(a.signed(), pow10(a.E-e))
322
+ y := new(big.Int).Mul(b.signed(), pow10(b.E-e))
323
+ return x.Cmp(y)
324
+ }
325
+
326
+ func (d *Dec) quantizeHalfUp(e int) *Dec {
327
+ if e <= d.E {
328
+ return &Dec{d.S, new(big.Int).Mul(d.C, pow10(d.E-e)), e}
329
+ }
330
+ p := pow10(e - d.E)
331
+ q, r := new(big.Int).QuoRem(d.C, p, new(big.Int))
332
+ if new(big.Int).Mul(r, bigTwo).Cmp(p) >= 0 {
333
+ q.Add(q, bigOne)
334
+ }
335
+ return &Dec{d.S, q, e}
336
+ }
337
+
338
+ func (d *Dec) isIntegral() bool {
339
+ if d.E >= 0 {
340
+ return true
341
+ }
342
+ return new(big.Int).Rem(d.C, pow10(-d.E)).Sign() == 0
343
+ }
344
+
345
+ func (d *Dec) toBigInt() *big.Int {
346
+ var v *big.Int
347
+ if d.E >= 0 {
348
+ v = new(big.Int).Mul(d.C, pow10(d.E))
349
+ } else {
350
+ v = new(big.Int).Quo(d.C, pow10(-d.E))
351
+ }
352
+ if d.S == 1 {
353
+ v.Neg(v)
354
+ }
355
+ return v
356
+ }
357
+
358
+ // String is str(Decimal): Python's to-scientific-string.
359
+ func (d *Dec) String() string {
360
+ digits := d.C.String()
361
+ left := d.E + len(digits)
362
+ dot := 1
363
+ if d.E <= 0 && left > -6 {
364
+ dot = left
365
+ }
366
+ var ip, fp string
367
+ switch {
368
+ case dot <= 0:
369
+ ip, fp = "0", "."+strings.Repeat("0", -dot)+digits
370
+ case dot >= len(digits):
371
+ ip, fp = digits+strings.Repeat("0", dot-len(digits)), ""
372
+ default:
373
+ ip, fp = digits[:dot], "."+digits[dot:]
374
+ }
375
+ ex := ""
376
+ if left != dot {
377
+ x := left - dot
378
+ if x >= 0 {
379
+ ex = "E+" + strconv.Itoa(x)
380
+ } else {
381
+ ex = "E" + strconv.Itoa(x)
382
+ }
383
+ }
384
+ sign := ""
385
+ if d.S == 1 {
386
+ sign = "-"
387
+ }
388
+ return sign + ip + fp + ex
389
+ }
390
+
391
+ func groupThousands(ip string) string {
392
+ if len(ip) <= 3 {
393
+ return ip
394
+ }
395
+ var b strings.Builder
396
+ first := len(ip) % 3
397
+ if first > 0 {
398
+ b.WriteString(ip[:first])
399
+ }
400
+ for i := first; i < len(ip); i += 3 {
401
+ if b.Len() > 0 {
402
+ b.WriteByte(',')
403
+ }
404
+ b.WriteString(ip[i : i+3])
405
+ }
406
+ return b.String()
407
+ }
408
+
409
+ // toFixed is format(d, "f") (places < 0: as it is) or format(d, ",.Nf").
410
+ func (d *Dec) toFixed(places int, group bool) string {
411
+ x := d
412
+ if places >= 0 {
413
+ x = d.roundHalfEven(-places)
414
+ }
415
+ digits := x.C.String()
416
+ dot := x.E + len(digits)
417
+ var ip, fp string
418
+ switch {
419
+ case dot < 0:
420
+ ip, fp = "0", strings.Repeat("0", -dot)+digits
421
+ case dot > len(digits):
422
+ ip, fp = digits+strings.Repeat("0", dot-len(digits)), ""
423
+ default:
424
+ ip, fp = digits[:dot], digits[dot:]
425
+ if ip == "" {
426
+ ip = "0"
427
+ }
428
+ }
429
+ if group {
430
+ ip = groupThousands(ip)
431
+ }
432
+ sign := ""
433
+ if x.S == 1 {
434
+ sign = "-"
435
+ }
436
+ if fp != "" {
437
+ return sign + ip + "." + fp
438
+ }
439
+ return sign + ip
440
+ }
441
+
442
+ func (d *Dec) roundHalfEven(e int) *Dec {
443
+ if e <= d.E {
444
+ return &Dec{d.S, new(big.Int).Mul(d.C, pow10(d.E-e)), e}
445
+ }
446
+ p := pow10(e - d.E)
447
+ q, r := new(big.Int).QuoRem(d.C, p, new(big.Int))
448
+ r2 := new(big.Int).Mul(r, bigTwo)
449
+ c := r2.Cmp(p)
450
+ if c > 0 || (c == 0 && q.Bit(0) == 1) {
451
+ q.Add(q, bigOne)
452
+ }
453
+ return &Dec{d.S, q, e}
454
+ }
455
+
456
+ // key: equal for equal numbers (1 and 1.0 and 1.00 are the same map key, as in Python).
457
+ func (d *Dec) key() string {
458
+ if d.C.Sign() == 0 {
459
+ return "0"
460
+ }
461
+ c, e := new(big.Int).Set(d.C), d.E
462
+ for new(big.Int).Rem(c, bigTen).Sign() == 0 {
463
+ c.Quo(c, bigTen)
464
+ e++
465
+ }
466
+ sign := ""
467
+ if d.S == 1 {
468
+ sign = "-"
469
+ }
470
+ return sign + c.String() + "e" + strconv.Itoa(e)
471
+ }
472
+
473
+ // ── Money ──────────────────────────────────────────────────────────────────────────────────────────────────────
474
+
475
+ // Money is an exact amount of money.
476
+ type Money struct{ Amount *Dec }
477
+
478
+ func moneyOf(x V) *Money {
479
+ if m, ok := x.(*Money); ok {
480
+ return m
481
+ }
482
+ if s, ok := x.(string); ok {
483
+ d := ParseDec(strings.TrimSpace(strings.ReplaceAll(strings.ReplaceAll(s, ",", ""), "$", "")))
484
+ if d == nil {
485
+ panic(PyErr("InvalidOperation", "[<class 'decimal.ConversionSyntax'>]"))
486
+ }
487
+ return &Money{d}
488
+ }
489
+ return &Money{toDec(x)}
490
+ }
491
+
492
+ func (m *Money) String() string {
493
+ a := m.Amount
494
+ places := 2
495
+ if a.E < 0 && -a.E > 2 {
496
+ places = -a.E
497
+ }
498
+ prefix := "$"
499
+ if a.S == 1 && a.C.Sign() != 0 {
500
+ prefix = "-$"
501
+ }
502
+ return prefix + a.abs().toFixed(places, true)
503
+ }
504
+
505
+ func moneyOther(other V, verb string) *Dec {
506
+ if m, ok := other.(*Money); ok {
507
+ return m.Amount
508
+ }
509
+ if isNumber(other) && numCmp(other, bigZero) == 0 {
510
+ return decInt(bigZero)
511
+ }
512
+ panic(KindMismatch("I can't " + verb + " money and " + describe(other) + ". Write the number as money, for example $5."))
513
+ }
514
+
515
+ // ── Other kinds ────────────────────────────────────────────────────────────────────────────────────────────────
516
+
517
+ // Date is a calendar date.
518
+ type Date struct{ Y, M, D int }
519
+
520
+ func (d *Date) iso() string { return fmt.Sprintf("%04d-%02d-%02d", d.Y, d.M, d.D) }
521
+ func (d *Date) num() int { return d.Y*10000 + d.M*100 + d.D }
522
+
523
+ var dateRe = regexp.MustCompile(`^(\d{4})-?(\d{2})-?(\d{2})$`)
524
+
525
+ func parseDate(text string) *Date {
526
+ m := dateRe.FindStringSubmatch(text)
527
+ if m == nil {
528
+ return nil
529
+ }
530
+ y, _ := strconv.Atoi(m[1])
531
+ mo, _ := strconv.Atoi(m[2])
532
+ d, _ := strconv.Atoi(m[3])
533
+ feb := 28
534
+ if (y%4 == 0 && y%100 != 0) || y%400 == 0 {
535
+ feb = 29
536
+ }
537
+ days := []int{31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
538
+ if y < 1 || mo < 1 || mo > 12 || d < 1 || d > days[mo-1] {
539
+ return nil
540
+ }
541
+ return &Date{y, mo, d}
542
+ }
543
+
544
+ // Tuple is a pair (or more) of values, as a map gives them.
545
+ type Tuple struct{ Items []V }
546
+
547
+ // List is a Thunder list (it changes in place, as Python's does).
548
+ type List struct{ Items []V }
549
+
550
+ type notGiven struct{}
551
+
552
+ // NotGiven stands for an input a call left out.
553
+ var NotGiven = &notGiven{}
554
+
555
+ type dictEntry struct {
556
+ k V
557
+ v V
558
+ }
559
+
560
+ // Dict is a Python dict: insertion order kept; keys equal the way Python compares them (1 == 1.0 == True).
561
+ type Dict struct {
562
+ order []string
563
+ m map[string]*dictEntry
564
+ }
565
+
566
+ func NewMap() V { return &Dict{m: map[string]*dictEntry{}} }
567
+ func newDict() *Dict { return &Dict{m: map[string]*dictEntry{}} }
568
+
569
+ func keyOf(k V) string {
570
+ switch v := k.(type) {
571
+ case nil:
572
+ return "N"
573
+ case string:
574
+ return "s" + v
575
+ case bool, *big.Int, *Dec:
576
+ return "n" + decOf(v).key()
577
+ case *Money:
578
+ return "m" + v.Amount.key()
579
+ case *Date:
580
+ return "d" + v.iso()
581
+ case *Tuple:
582
+ parts := make([]string, len(v.Items))
583
+ for i, x := range v.Items {
584
+ parts[i] = keyOf(x)
585
+ }
586
+ return "t(" + strings.Join(parts, ",") + ")"
587
+ }
588
+ if k == NotGiven {
589
+ return "G"
590
+ }
591
+ panic(TypeErr("unhashable type: '" + typeName(k) + "'"))
592
+ }
593
+
594
+ func (d *Dict) has(k V) bool { _, ok := d.m[keyOf(k)]; return ok }
595
+ func (d *Dict) get(k V) (V, bool) {
596
+ e, ok := d.m[keyOf(k)]
597
+ if !ok {
598
+ return nil, false
599
+ }
600
+ return e.v, true
601
+ }
602
+ func (d *Dict) set(k, v V) {
603
+ id := keyOf(k)
604
+ if e, ok := d.m[id]; ok {
605
+ e.v = v
606
+ return
607
+ }
608
+ d.m[id] = &dictEntry{k, v}
609
+ d.order = append(d.order, id)
610
+ }
611
+ func (d *Dict) del(k V) {
612
+ id := keyOf(k)
613
+ if _, ok := d.m[id]; !ok {
614
+ return
615
+ }
616
+ delete(d.m, id)
617
+ for i, x := range d.order {
618
+ if x == id {
619
+ d.order = append(d.order[:i:i], d.order[i+1:]...)
620
+ break
621
+ }
622
+ }
623
+ }
624
+ func (d *Dict) size() int { return len(d.order) }
625
+ func (d *Dict) entries() []*dictEntry {
626
+ out := make([]*dictEntry, len(d.order))
627
+ for i, id := range d.order {
628
+ out[i] = d.m[id]
629
+ }
630
+ return out
631
+ }
632
+ func (d *Dict) keys() []V {
633
+ out := make([]V, len(d.order))
634
+ for i, id := range d.order {
635
+ out[i] = d.m[id].k
636
+ }
637
+ return out
638
+ }
639
+ func (d *Dict) values() []V {
640
+ out := make([]V, len(d.order))
641
+ for i, id := range d.order {
642
+ out[i] = d.m[id].v
643
+ }
644
+ return out
645
+ }
646
+ func (d *Dict) items() []V {
647
+ out := make([]V, len(d.order))
648
+ for i, id := range d.order {
649
+ e := d.m[id]
650
+ out[i] = &Tuple{[]V{e.k, e.v}}
651
+ }
652
+ return out
653
+ }
654
+
655
+ // Field is a record's field: its name and kind.
656
+ type Field struct {
657
+ Py string
658
+ Kind string
659
+ }
660
+
661
+ // Rule is a Never rule on a record's field.
662
+ type Rule struct {
663
+ Cond func(value V) V
664
+ Text string
665
+ Line int
666
+ }
667
+
668
+ // RecordKind is a kind of record (a Python dataclass): its name, fields, and Never rules by field.
669
+ type RecordKind struct {
670
+ Py string
671
+ Fields []Field
672
+ Rules map[string][]Rule
673
+ }
674
+
675
+ // Record is a record value: its kind and field values.
676
+ type Record struct {
677
+ Cls *RecordKind
678
+ F map[string]V
679
+ }
680
+
681
+ // ── Kinds ──────────────────────────────────────────────────────────────────────────────────────────────────────
682
+
683
+ func isInt(x V) bool { _, ok := x.(*big.Int); return ok }
684
+ func isNumber(x V) bool { switch x.(type) { case *big.Int, *Dec: return true }; return false }
685
+ func isIntLike(x V) bool {
686
+ switch x.(type) {
687
+ case *big.Int, bool:
688
+ return true
689
+ }
690
+ return false
691
+ }
692
+ func isNumLike(x V) bool { return isIntLike(x) || isDec(x) }
693
+ func isDec(x V) bool { _, ok := x.(*Dec); return ok }
694
+ func asBig(x V) *big.Int {
695
+ switch v := x.(type) {
696
+ case bool:
697
+ if v {
698
+ return big.NewInt(1)
699
+ }
700
+ return big.NewInt(0)
701
+ case *big.Int:
702
+ return v
703
+ }
704
+ return nil
705
+ }
706
+ func numCmp(a, b V) int {
707
+ if isIntLike(a) && isIntLike(b) {
708
+ return asBig(a).Cmp(asBig(b))
709
+ }
710
+ return decCmp(decOf(a), decOf(b))
711
+ }
712
+
713
+ func typeName(v V) string {
714
+ switch x := v.(type) {
715
+ case nil:
716
+ return "NoneType"
717
+ case bool:
718
+ return "bool"
719
+ case *big.Int:
720
+ return "int"
721
+ case string:
722
+ return "str"
723
+ case *Dec:
724
+ return "decimal.Decimal"
725
+ case *Money:
726
+ return "Money"
727
+ case *List:
728
+ return "list"
729
+ case *Tuple:
730
+ return "tuple"
731
+ case *Dict:
732
+ return "dict"
733
+ case *Date:
734
+ return "datetime.date"
735
+ case *Record:
736
+ return x.Cls.Py
737
+ }
738
+ if v == NotGiven {
739
+ return "_NotGiven"
740
+ }
741
+ return "object"
742
+ }
743
+
744
+ func shortName(v V) string {
745
+ switch v.(type) {
746
+ case *Dec:
747
+ return "Decimal"
748
+ case *Date:
749
+ return "date"
750
+ }
751
+ return typeName(v)
752
+ }
753
+
754
+ func describe(v V) string {
755
+ switch x := v.(type) {
756
+ case nil:
757
+ return "nothing"
758
+ case bool:
759
+ return "a yes/no value"
760
+ case string:
761
+ return "the text \"" + x + "\""
762
+ case *Money:
763
+ return x.String()
764
+ }
765
+ if isNumber(v) {
766
+ return "the number " + Show(v)
767
+ }
768
+ return "a value (" + shortName(v) + ")"
769
+ }
770
+
771
+ func trimDecimalZeros(t string) string {
772
+ if !strings.Contains(t, ".") {
773
+ return t
774
+ }
775
+ t = strings.TrimRight(t, "0")
776
+ return strings.TrimSuffix(t, ".")
777
+ }
778
+
779
+ // Show is show(v): a value the way Thunder says it.
780
+ func Show(v V) string {
781
+ switch x := v.(type) {
782
+ case nil:
783
+ return "nothing"
784
+ case bool:
785
+ if x {
786
+ return "yes"
787
+ }
788
+ return "no"
789
+ case *Dec:
790
+ return trimDecimalZeros(x.toFixed(-1, false))
791
+ case *List:
792
+ return "[" + joinShow(x.Items, Show) + "]"
793
+ case *Tuple:
794
+ return "[" + joinShow(x.Items, Show) + "]"
795
+ case *Dict:
796
+ parts := []string{}
797
+ for _, e := range x.entries() {
798
+ parts = append(parts, Show(e.k)+": "+Show(e.v))
799
+ }
800
+ return "{" + strings.Join(parts, ", ") + "}"
801
+ case *Record:
802
+ parts := []string{}
803
+ for _, f := range x.Cls.Fields {
804
+ parts = append(parts, strings.ReplaceAll(f.Py, "_", " ")+": "+Show(x.F[f.Py]))
805
+ }
806
+ return x.Cls.Py + "(" + strings.Join(parts, ", ") + ")"
807
+ case *Date:
808
+ return x.iso()
809
+ }
810
+ return PyStr(v)
811
+ }
812
+
813
+ func joinShow(items []V, f func(V) string) string {
814
+ parts := make([]string, len(items))
815
+ for i, x := range items {
816
+ parts[i] = f(x)
817
+ }
818
+ return strings.Join(parts, ", ")
819
+ }
820
+
821
+ func pyRepr(v V) string {
822
+ switch x := v.(type) {
823
+ case string:
824
+ q := "'"
825
+ if strings.Contains(x, "'") && !strings.Contains(x, "\"") {
826
+ q = "\""
827
+ }
828
+ var b strings.Builder
829
+ for _, ch := range x {
830
+ switch {
831
+ case ch == '\\':
832
+ b.WriteString("\\\\")
833
+ case string(ch) == q:
834
+ b.WriteString("\\" + q)
835
+ case ch == '\n':
836
+ b.WriteString("\\n")
837
+ case ch == '\r':
838
+ b.WriteString("\\r")
839
+ case ch == '\t':
840
+ b.WriteString("\\t")
841
+ case ch < 0x20 || ch == 0x7f:
842
+ b.WriteString(fmt.Sprintf("\\x%02x", ch))
843
+ default:
844
+ b.WriteRune(ch)
845
+ }
846
+ }
847
+ return q + b.String() + q
848
+ case nil:
849
+ return "None"
850
+ case bool:
851
+ if x {
852
+ return "True"
853
+ }
854
+ return "False"
855
+ case *big.Int:
856
+ return x.String()
857
+ case *Dec:
858
+ return "Decimal('" + x.String() + "')"
859
+ case *Money:
860
+ return "Money('" + x.Amount.toFixed(-1, false) + "')"
861
+ case *List:
862
+ return "[" + joinShow(x.Items, pyRepr) + "]"
863
+ case *Tuple:
864
+ if len(x.Items) == 1 {
865
+ return "(" + pyRepr(x.Items[0]) + ",)"
866
+ }
867
+ return "(" + joinShow(x.Items, pyRepr) + ")"
868
+ case *Dict:
869
+ parts := []string{}
870
+ for _, e := range x.entries() {
871
+ parts = append(parts, pyRepr(e.k)+": "+pyRepr(e.v))
872
+ }
873
+ return "{" + strings.Join(parts, ", ") + "}"
874
+ case *Date:
875
+ return fmt.Sprintf("datetime.date(%d, %d, %d)", x.Y, x.M, x.D)
876
+ case *Record:
877
+ parts := []string{}
878
+ for _, f := range x.Cls.Fields {
879
+ parts = append(parts, f.Py+"="+pyRepr(x.F[f.Py]))
880
+ }
881
+ return x.Cls.Py + "(" + strings.Join(parts, ", ") + ")"
882
+ }
883
+ if v == NotGiven {
884
+ return "not given"
885
+ }
886
+ return fmt.Sprint(v)
887
+ }
888
+
889
+ // PyStr is Python's str(v).
890
+ func PyStr(v V) string {
891
+ switch x := v.(type) {
892
+ case string:
893
+ return x
894
+ case *Money:
895
+ return x.String()
896
+ case *Date:
897
+ return x.iso()
898
+ case *Dec:
899
+ return x.String()
900
+ }
901
+ return pyRepr(v)
902
+ }
903
+
904
+ // Truthy is Python's truth value (used where the generated Python uses it: "where" conditions and Never rules).
905
+ func Truthy(v V) bool {
906
+ switch x := v.(type) {
907
+ case nil:
908
+ return false
909
+ case bool:
910
+ return x
911
+ case *big.Int:
912
+ return x.Sign() != 0
913
+ case *Dec:
914
+ return !x.isZero()
915
+ case string:
916
+ return len(x) > 0
917
+ case *List:
918
+ return len(x.Items) > 0
919
+ case *Tuple:
920
+ return len(x.Items) > 0
921
+ case *Dict:
922
+ return x.size() > 0
923
+ }
924
+ return true
925
+ }
926
+
927
+ // YesNo is yes_no(v): a condition needs a real yes/no value.
928
+ func YesNo(v V) bool {
929
+ if b, ok := v.(bool); ok {
930
+ return b
931
+ }
932
+ panic(KindMismatch("This needs a yes/no value, but it is " + describe(v) + ". Compare it instead, for example: is 0, is empty, is nothing."))
933
+ }
934
+
935
+ func toDec(x V) *Dec {
936
+ switch v := x.(type) {
937
+ case *Dec:
938
+ return v
939
+ case bool:
940
+ panic(KindMismatch("A yes/no value was used where a number was needed."))
941
+ case *big.Int:
942
+ return decInt(v)
943
+ case nil:
944
+ panic(KindMismatch("A value was nothing where a number was needed."))
945
+ }
946
+ panic(KindMismatch(describe(x) + " was used where a number was needed."))
947
+ }
948
+
949
+ // ── Python operators ───────────────────────────────────────────────────────────────────────────────────────────
950
+
951
+ func runes(s string) []string {
952
+ out := make([]string, 0, len(s))
953
+ for _, r := range s {
954
+ out = append(out, string(r))
955
+ }
956
+ return out
957
+ }
958
+
959
+ func PyLen(v V) V {
960
+ switch x := v.(type) {
961
+ case string:
962
+ return big.NewInt(int64(utf8.RuneCountInString(x)))
963
+ case *List:
964
+ return big.NewInt(int64(len(x.Items)))
965
+ case *Tuple:
966
+ return big.NewInt(int64(len(x.Items)))
967
+ case *Dict:
968
+ return big.NewInt(int64(x.size()))
969
+ }
970
+ panic(TypeErr("object of type '" + typeName(v) + "' has no len()"))
971
+ }
972
+
973
+ // Iter goes through a value the way Python's for loop does (a list is read live, as it changes).
974
+ type Iter struct {
975
+ list *List
976
+ items []V
977
+ }
978
+
979
+ func PyIter(v V) *Iter {
980
+ switch x := v.(type) {
981
+ case *List:
982
+ return &Iter{list: x}
983
+ case *Tuple:
984
+ return &Iter{items: x.Items}
985
+ case string:
986
+ rs := runes(x)
987
+ items := make([]V, len(rs))
988
+ for i, r := range rs {
989
+ items[i] = r
990
+ }
991
+ return &Iter{items: items}
992
+ case *Dict:
993
+ return &Iter{items: x.keys()}
994
+ }
995
+ panic(TypeErr("'" + typeName(v) + "' object is not iterable"))
996
+ }
997
+
998
+ // Next is the k-th item (from 0), or false when there is none.
999
+ func (it *Iter) Next(k int) (V, bool) {
1000
+ if it.list != nil {
1001
+ if k < len(it.list.Items) {
1002
+ return it.list.Items[k], true
1003
+ }
1004
+ return nil, false
1005
+ }
1006
+ if k < len(it.items) {
1007
+ return it.items[k], true
1008
+ }
1009
+ return nil, false
1010
+ }
1011
+
1012
+ func iterItems(v V) []V {
1013
+ it := PyIter(v)
1014
+ if it.list != nil {
1015
+ return append([]V{}, it.list.Items...)
1016
+ }
1017
+ return it.items
1018
+ }
1019
+
1020
+ func PyList(v V) V { return &List{iterItems(v)} }
1021
+
1022
+ func NewList(items ...V) V { return &List{items} }
1023
+
1024
+ func Add(a, b V) V {
1025
+ if m, ok := a.(*Money); ok {
1026
+ return &Money{decAdd(m.Amount, moneyOther(b, "add"))}
1027
+ }
1028
+ if m, ok := b.(*Money); ok {
1029
+ return &Money{decAdd(m.Amount, moneyOther(a, "add"))}
1030
+ }
1031
+ if isIntLike(a) && isIntLike(b) {
1032
+ return new(big.Int).Add(asBig(a), asBig(b))
1033
+ }
1034
+ if isNumLike(a) && isNumLike(b) {
1035
+ return decAdd(decOf(a), decOf(b))
1036
+ }
1037
+ if s, ok := a.(string); ok {
1038
+ if t, ok := b.(string); ok {
1039
+ return s + t
1040
+ }
1041
+ panic(TypeErr("can only concatenate str (not \"" + typeName(b) + "\") to str"))
1042
+ }
1043
+ if l, ok := a.(*List); ok {
1044
+ if r, ok := b.(*List); ok {
1045
+ items := append(append([]V{}, l.Items...), r.Items...)
1046
+ return &List{items}
1047
+ }
1048
+ panic(TypeErr("can only concatenate list (not \"" + typeName(b) + "\") to list"))
1049
+ }
1050
+ if l, ok := a.(*Tuple); ok {
1051
+ if r, ok := b.(*Tuple); ok {
1052
+ return &Tuple{append(append([]V{}, l.Items...), r.Items...)}
1053
+ }
1054
+ panic(TypeErr("can only concatenate tuple (not \"" + typeName(b) + "\") to tuple"))
1055
+ }
1056
+ panic(TypeErr("unsupported operand type(s) for +: '" + typeName(a) + "' and '" + typeName(b) + "'"))
1057
+ }
1058
+
1059
+ func Sub(a, b V) V {
1060
+ if m, ok := a.(*Money); ok {
1061
+ return &Money{decSub(m.Amount, moneyOther(b, "subtract"))}
1062
+ }
1063
+ if m, ok := b.(*Money); ok {
1064
+ return &Money{decSub(moneyOther(a, "subtract"), m.Amount)}
1065
+ }
1066
+ if isIntLike(a) && isIntLike(b) {
1067
+ return new(big.Int).Sub(asBig(a), asBig(b))
1068
+ }
1069
+ if isNumLike(a) && isNumLike(b) {
1070
+ return decSub(decOf(a), decOf(b))
1071
+ }
1072
+ panic(TypeErr("unsupported operand type(s) for -: '" + typeName(a) + "' and '" + typeName(b) + "'"))
1073
+ }
1074
+
1075
+ func repeatSeq(seq V, n V) V {
1076
+ k := asBig(n).Int64()
1077
+ if s, ok := seq.(string); ok {
1078
+ if k > 0 {
1079
+ return strings.Repeat(s, int(k))
1080
+ }
1081
+ return ""
1082
+ }
1083
+ l := seq.(*List)
1084
+ out := []V{}
1085
+ for i := int64(0); i < k; i++ {
1086
+ out = append(out, l.Items...)
1087
+ }
1088
+ return &List{out}
1089
+ }
1090
+
1091
+ func Mul(a, b V) V {
1092
+ if m, ok := a.(*Money); ok {
1093
+ if _, ok := b.(*Money); ok {
1094
+ panic(KindMismatch("Money can't be multiplied by money."))
1095
+ }
1096
+ return &Money{decMul(m.Amount, toDec(b))}
1097
+ }
1098
+ if m, ok := b.(*Money); ok {
1099
+ return &Money{decMul(m.Amount, toDec(a))}
1100
+ }
1101
+ if isIntLike(a) && isIntLike(b) {
1102
+ return new(big.Int).Mul(asBig(a), asBig(b))
1103
+ }
1104
+ if isNumLike(a) && isNumLike(b) {
1105
+ return decMul(decOf(a), decOf(b))
1106
+ }
1107
+ seq := func(x V) bool {
1108
+ switch x.(type) {
1109
+ case string, *List:
1110
+ return true
1111
+ }
1112
+ return false
1113
+ }
1114
+ if seq(a) {
1115
+ if isIntLike(b) {
1116
+ return repeatSeq(a, b)
1117
+ }
1118
+ panic(TypeErr("can't multiply sequence by non-int of type '" + typeName(b) + "'"))
1119
+ }
1120
+ if seq(b) {
1121
+ if isIntLike(a) {
1122
+ return repeatSeq(b, a)
1123
+ }
1124
+ panic(TypeErr("can't multiply sequence by non-int of type '" + typeName(a) + "'"))
1125
+ }
1126
+ panic(TypeErr("unsupported operand type(s) for *: '" + typeName(a) + "' and '" + typeName(b) + "'"))
1127
+ }
1128
+
1129
+ func Neg(a V) V {
1130
+ if m, ok := a.(*Money); ok {
1131
+ return &Money{m.Amount.neg()}
1132
+ }
1133
+ if isIntLike(a) {
1134
+ return new(big.Int).Neg(asBig(a))
1135
+ }
1136
+ if d, ok := a.(*Dec); ok {
1137
+ return d.neg()
1138
+ }
1139
+ panic(TypeErr("bad operand type for unary -: '" + typeName(a) + "'"))
1140
+ }
1141
+
1142
+ // IntMod is Python's % on two whole numbers: the sign of the divisor.
1143
+ func IntMod(a, b V) V {
1144
+ if !isIntLike(a) || !isIntLike(b) {
1145
+ if isNumLike(a) && isNumLike(b) {
1146
+ return Modulo(a, b)
1147
+ }
1148
+ panic(TypeErr("unsupported operand type(s) for %: '" + typeName(a) + "' and '" + typeName(b) + "'"))
1149
+ }
1150
+ x, y := asBig(a), asBig(b)
1151
+ if y.Sign() == 0 {
1152
+ panic(PyErr("ZeroDivisionError", "integer modulo by zero"))
1153
+ }
1154
+ r := new(big.Int).Rem(x, y)
1155
+ if r.Sign() != 0 && (r.Sign() < 0) != (y.Sign() < 0) {
1156
+ r.Add(r, y)
1157
+ }
1158
+ return r
1159
+ }
1160
+
1161
+ // Divide is divide(a, b) in thunder_runtime.py: always exact.
1162
+ func Divide(a, b V) V {
1163
+ if m, ok := a.(*Money); ok {
1164
+ if n, ok := b.(*Money); ok {
1165
+ if n.Amount.isZero() {
1166
+ panic(DividedByZero("You divided by zero."))
1167
+ }
1168
+ return decDiv(m.Amount, n.Amount)
1169
+ }
1170
+ d := toDec(b)
1171
+ if d.isZero() {
1172
+ panic(DividedByZero("You divided by zero."))
1173
+ }
1174
+ return &Money{decDiv(m.Amount, d)}
1175
+ }
1176
+ if _, ok := b.(*Money); ok {
1177
+ panic(KindMismatch("A plain number can't be divided by money."))
1178
+ }
1179
+ x, y := toDec(a), toDec(b)
1180
+ if y.isZero() {
1181
+ panic(DividedByZero("You divided by zero."))
1182
+ }
1183
+ return decDiv(x, y)
1184
+ }
1185
+
1186
+ // Modulo is modulo(a, b) in thunder_runtime.py.
1187
+ func Modulo(a, b V) V {
1188
+ ma, money := a.(*Money)
1189
+ var x *Dec
1190
+ if money {
1191
+ x = ma.Amount
1192
+ } else {
1193
+ x = toDec(a)
1194
+ }
1195
+ var y *Dec
1196
+ if mb, ok := b.(*Money); ok {
1197
+ y = mb.Amount
1198
+ } else {
1199
+ y = toDec(b)
1200
+ }
1201
+ if y.isZero() {
1202
+ panic(DividedByZero("You divided by zero."))
1203
+ }
1204
+ r := decRem(x, y)
1205
+ if !r.isZero() && (r.S == 1) != (y.S == 1 && !y.isZero()) {
1206
+ r = decAdd(r, y)
1207
+ }
1208
+ if money {
1209
+ return &Money{r}
1210
+ }
1211
+ if isInt(a) && isInt(b) {
1212
+ return r.toBigInt()
1213
+ }
1214
+ return r
1215
+ }
1216
+
1217
+ // RoundTo is round_to(x, places).
1218
+ func RoundTo(x V, places ...V) V {
1219
+ p := 0
1220
+ if len(places) > 0 {
1221
+ pv := places[0]
1222
+ if d, ok := pv.(*Dec); ok {
1223
+ pv = d.toBigInt()
1224
+ }
1225
+ p = int(asBig(pv).Int64())
1226
+ }
1227
+ if m, ok := x.(*Money); ok {
1228
+ return &Money{m.Amount.quantizeHalfUp(-p)}
1229
+ }
1230
+ if n, ok := x.(*big.Int); ok {
1231
+ return n
1232
+ }
1233
+ d := toDec(x).quantizeHalfUp(-p)
1234
+ if p == 0 {
1235
+ return d.toBigInt()
1236
+ }
1237
+ return d
1238
+ }
1239
+
1240
+ // Eq is Python ==.
1241
+ func Eq(a, b V) bool {
1242
+ if _, isD := a.(*Dec); !isD && sameRef(a, b) {
1243
+ return true
1244
+ }
1245
+ ma, aM := a.(*Money)
1246
+ mb, bM := b.(*Money)
1247
+ if aM || bM {
1248
+ m, o := ma, b
1249
+ if !aM {
1250
+ m, o = mb, a
1251
+ }
1252
+ switch o.(type) {
1253
+ case nil, string, bool:
1254
+ return false
1255
+ }
1256
+ return decCmp(m.Amount, moneyOther(o, "compare")) == 0
1257
+ }
1258
+ if a == nil || b == nil {
1259
+ return false
1260
+ }
1261
+ if isNumLike(a) && isNumLike(b) {
1262
+ return numCmp(a, b) == 0
1263
+ }
1264
+ sa, aS := a.(string)
1265
+ sb, bS := b.(string)
1266
+ if aS || bS {
1267
+ return aS && bS && sa == sb
1268
+ }
1269
+ switch x := a.(type) {
1270
+ case *List:
1271
+ y, ok := b.(*List)
1272
+ if !ok || len(x.Items) != len(y.Items) {
1273
+ return false
1274
+ }
1275
+ for i := range x.Items {
1276
+ if !(sameRef(x.Items[i], y.Items[i]) || Eq(x.Items[i], y.Items[i])) {
1277
+ return false
1278
+ }
1279
+ }
1280
+ return true
1281
+ case *Tuple:
1282
+ y, ok := b.(*Tuple)
1283
+ if !ok || len(x.Items) != len(y.Items) {
1284
+ return false
1285
+ }
1286
+ for i := range x.Items {
1287
+ if !Eq(x.Items[i], y.Items[i]) {
1288
+ return false
1289
+ }
1290
+ }
1291
+ return true
1292
+ case *Dict:
1293
+ y, ok := b.(*Dict)
1294
+ if !ok || x.size() != y.size() {
1295
+ return false
1296
+ }
1297
+ for _, id := range x.order {
1298
+ e2, ok := y.m[id]
1299
+ if !ok || !Eq(x.m[id].v, e2.v) {
1300
+ return false
1301
+ }
1302
+ }
1303
+ return true
1304
+ case *Record:
1305
+ y, ok := b.(*Record)
1306
+ if !ok || x.Cls != y.Cls {
1307
+ return false
1308
+ }
1309
+ for _, f := range x.Cls.Fields {
1310
+ if !Eq(x.F[f.Py], y.F[f.Py]) {
1311
+ return false
1312
+ }
1313
+ }
1314
+ return true
1315
+ case *Date:
1316
+ y, ok := b.(*Date)
1317
+ return ok && x.num() == y.num()
1318
+ }
1319
+ return false
1320
+ }
1321
+
1322
+ // sameRef is JavaScript's ===: the same value for plain values, the same object for the rest.
1323
+ func sameRef(a, b V) bool {
1324
+ switch x := a.(type) {
1325
+ case nil:
1326
+ return b == nil
1327
+ case bool:
1328
+ y, ok := b.(bool)
1329
+ return ok && x == y
1330
+ case string:
1331
+ y, ok := b.(string)
1332
+ return ok && x == y
1333
+ case *big.Int:
1334
+ y, ok := b.(*big.Int)
1335
+ return ok && x.Cmp(y) == 0
1336
+ case *Dec, *Money, *List, *Tuple, *Dict, *Record, *Date:
1337
+ return a == b
1338
+ }
1339
+ return a == b
1340
+ }
1341
+
1342
+ func flip(op string) string {
1343
+ switch op {
1344
+ case "<":
1345
+ return ">"
1346
+ case ">":
1347
+ return "<"
1348
+ case "<=":
1349
+ return ">="
1350
+ case ">=":
1351
+ return "<="
1352
+ }
1353
+ return op
1354
+ }
1355
+
1356
+ func holds(op string, c int) bool {
1357
+ switch op {
1358
+ case "<":
1359
+ return c < 0
1360
+ case ">":
1361
+ return c > 0
1362
+ case "<=":
1363
+ return c <= 0
1364
+ }
1365
+ return c >= 0
1366
+ }
1367
+
1368
+ // Compare is Python's <, >, <=, >= (and == / != through Eq).
1369
+ func Compare(op string, a, b V) bool {
1370
+ if op == "==" {
1371
+ return Eq(a, b)
1372
+ }
1373
+ if op == "!=" {
1374
+ return !Eq(a, b)
1375
+ }
1376
+ ma, aM := a.(*Money)
1377
+ mb, bM := b.(*Money)
1378
+ if aM || bM {
1379
+ m, o, o2 := ma, b, op
1380
+ if !aM {
1381
+ m, o, o2 = mb, a, flip(op)
1382
+ }
1383
+ if o == nil {
1384
+ panic(TypeErr("'" + o2 + "' not supported between instances of 'decimal.Decimal' and 'NoneType'"))
1385
+ }
1386
+ return holds(o2, decCmp(m.Amount, moneyOther(o, "compare")))
1387
+ }
1388
+ c, ok := order(a, b)
1389
+ if !ok {
1390
+ panic(TypeErr("'" + op + "' not supported between instances of '" + typeName(a) + "' and '" + typeName(b) + "'"))
1391
+ }
1392
+ return holds(op, c)
1393
+ }
1394
+
1395
+ func sign(n int) int {
1396
+ if n < 0 {
1397
+ return -1
1398
+ }
1399
+ if n > 0 {
1400
+ return 1
1401
+ }
1402
+ return 0
1403
+ }
1404
+
1405
+ func order(a, b V) (int, bool) {
1406
+ if isNumLike(a) && isNumLike(b) {
1407
+ return numCmp(a, b), true
1408
+ }
1409
+ if sa, ok := a.(string); ok {
1410
+ if sb, ok := b.(string); ok {
1411
+ return cmpStr(sa, sb), true
1412
+ }
1413
+ }
1414
+ if da, ok := a.(*Date); ok {
1415
+ if db, ok := b.(*Date); ok {
1416
+ return sign(da.num() - db.num()), true
1417
+ }
1418
+ }
1419
+ seqA, aSeq, aList := seqOf(a)
1420
+ seqB, bSeq, bList := seqOf(b)
1421
+ if aSeq && bSeq && aList == bList {
1422
+ n := minInt(len(seqA), len(seqB))
1423
+ for i := 0; i < n; i++ {
1424
+ if Eq(seqA[i], seqB[i]) {
1425
+ continue
1426
+ }
1427
+ if Compare("<", seqA[i], seqB[i]) {
1428
+ return -1, true
1429
+ }
1430
+ return 1, true
1431
+ }
1432
+ return sign(len(seqA) - len(seqB)), true
1433
+ }
1434
+ return 0, false
1435
+ }
1436
+
1437
+ func seqOf(x V) ([]V, bool, bool) {
1438
+ switch v := x.(type) {
1439
+ case *List:
1440
+ return v.Items, true, true
1441
+ case *Tuple:
1442
+ return v.Items, true, false
1443
+ }
1444
+ return nil, false, false
1445
+ }
1446
+
1447
+ func isTuple(x V) bool { _, ok := x.(*Tuple); return ok }
1448
+
1449
+ func cmpStr(a, b string) int {
1450
+ x, y := []rune(a), []rune(b)
1451
+ n := minInt(len(x), len(y))
1452
+ for i := 0; i < n; i++ {
1453
+ if d := int(x[i]) - int(y[i]); d != 0 {
1454
+ return sign(d)
1455
+ }
1456
+ }
1457
+ return sign(len(x) - len(y))
1458
+ }
1459
+
1460
+ func contains(container, item V) bool {
1461
+ switch c := container.(type) {
1462
+ case string:
1463
+ s, ok := item.(string)
1464
+ if !ok {
1465
+ panic(TypeErr("'in <string>' requires string as left operand, not " + typeName(item)))
1466
+ }
1467
+ return strings.Contains(c, s)
1468
+ case *Dict:
1469
+ return c.has(item)
1470
+ case *List:
1471
+ for _, x := range c.Items {
1472
+ if sameRef(x, item) || Eq(x, item) {
1473
+ return true
1474
+ }
1475
+ }
1476
+ return false
1477
+ case *Tuple:
1478
+ for _, x := range c.Items {
1479
+ if Eq(x, item) {
1480
+ return true
1481
+ }
1482
+ }
1483
+ return false
1484
+ }
1485
+ panic(TypeErr("argument of type '" + typeName(container) + "' is not iterable"))
1486
+ }
1487
+
1488
+ // pySort is Python's list.sort / sorted: stable, using < only. It makes the same comparisons in the same order as
1489
+ // the Thunder engine (JavaScript's sort: a run, then binary insertion), so a list that can't be ordered fails on the
1490
+ // same pair of values.
1491
+ func pySort(items []V, key func(V) V, reverse bool) []V {
1492
+ type keyed struct {
1493
+ v V
1494
+ k V
1495
+ i int
1496
+ }
1497
+ a := make([]keyed, len(items))
1498
+ for i, v := range items {
1499
+ k := v
1500
+ if key != nil {
1501
+ k = key(v)
1502
+ }
1503
+ a[i] = keyed{v, k, i}
1504
+ }
1505
+ cmp := func(x, y keyed) int {
1506
+ if reverse {
1507
+ if Compare("<", y.k, x.k) {
1508
+ return -1
1509
+ }
1510
+ if Compare("<", x.k, y.k) {
1511
+ return 1
1512
+ }
1513
+ } else {
1514
+ if Compare("<", x.k, y.k) {
1515
+ return -1
1516
+ }
1517
+ if Compare("<", y.k, x.k) {
1518
+ return 1
1519
+ }
1520
+ }
1521
+ return x.i - y.i
1522
+ }
1523
+ n := len(a)
1524
+ if n >= 2 {
1525
+ // The first run: ascending, or strictly descending (then reversed).
1526
+ run := 2
1527
+ desc := cmp(a[1], a[0]) < 0
1528
+ prev := a[1]
1529
+ for idx := 2; idx < n; idx++ {
1530
+ c := cmp(a[idx], prev)
1531
+ if desc {
1532
+ if c >= 0 {
1533
+ break
1534
+ }
1535
+ } else if c < 0 {
1536
+ break
1537
+ }
1538
+ prev = a[idx]
1539
+ run++
1540
+ }
1541
+ if desc {
1542
+ for i, j := 0, run-1; i < j; i, j = i+1, j-1 {
1543
+ a[i], a[j] = a[j], a[i]
1544
+ }
1545
+ }
1546
+ // Binary insertion of the rest.
1547
+ for start := run; start < n; start++ {
1548
+ pivot := a[start]
1549
+ left, right := 0, start
1550
+ for left < right {
1551
+ mid := left + ((right - left) >> 1)
1552
+ if cmp(pivot, a[mid]) < 0 {
1553
+ right = mid
1554
+ } else {
1555
+ left = mid + 1
1556
+ }
1557
+ }
1558
+ copy(a[left+1:start+1], a[left:start])
1559
+ a[left] = pivot
1560
+ }
1561
+ }
1562
+ out := make([]V, n)
1563
+ for i, x := range a {
1564
+ out[i] = x.v
1565
+ }
1566
+ return out
1567
+ }
1568
+
1569
+ // PySort sorts a list's items (a new list).
1570
+ func PySort(list V, key func(V) V, reverse bool) V {
1571
+ return &List{pySort(iterItems(list), key, reverse)}
1572
+ }
1573
+
1574
+ // ── Attribute-style Python calls ───────────────────────────────────────────────────────────────────────────────
1575
+
1576
+ func attrErr(v V, name string) *Err {
1577
+ return PyErr("AttributeError", "'"+typeName(v)+"' object has no attribute '"+name+"'")
1578
+ }
1579
+ func strMethod(v V, name string) string {
1580
+ s, ok := v.(string)
1581
+ if !ok {
1582
+ panic(attrErr(v, name))
1583
+ }
1584
+ return s
1585
+ }
1586
+
1587
+ func isLineBreak(r rune) bool {
1588
+ switch r {
1589
+ case '\n', '\r', '\v', '\f', 0x1c, 0x1d, 0x1e, 0x85, 0x2028, 0x2029:
1590
+ return true
1591
+ }
1592
+ return false
1593
+ }
1594
+
1595
+ func splitLines(s string) []V {
1596
+ out := []V{}
1597
+ rs := []rune(s)
1598
+ start := 0
1599
+ for i := 0; i < len(rs); i++ {
1600
+ if isLineBreak(rs[i]) {
1601
+ out = append(out, string(rs[start:i]))
1602
+ if rs[i] == '\r' && i+1 < len(rs) && rs[i+1] == '\n' {
1603
+ i++
1604
+ }
1605
+ start = i + 1
1606
+ }
1607
+ }
1608
+ if start < len(rs) {
1609
+ out = append(out, string(rs[start:]))
1610
+ }
1611
+ return out
1612
+ }
1613
+
1614
+ // isPySpace is JavaScript's \s plus the separators Python's str.split also breaks at.
1615
+ func isPySpace(r rune) bool {
1616
+ switch r {
1617
+ case '\t', '\n', '\v', '\f', '\r', ' ', 0xa0, 0x1680, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000, 0xfeff, 0x1c, 0x1d, 0x1e, 0x1f, 0x85:
1618
+ return true
1619
+ }
1620
+ return r >= 0x2000 && r <= 0x200a
1621
+ }
1622
+
1623
+ func pySplit(s string) []V {
1624
+ out := []V{}
1625
+ for _, p := range strings.FieldsFunc(s, isPySpace) {
1626
+ out = append(out, p)
1627
+ }
1628
+ return out
1629
+ }
1630
+ func pyStrip(s string) string { return strings.TrimFunc(s, isPySpace) }
1631
+
1632
+ // ── JSON, the way Python's json module reads and writes it ─────────────────────────────────────────────────────
1633
+
1634
+ type jsonError struct {
1635
+ msg string
1636
+ pos int
1637
+ }
1638
+
1639
+ func jsonParse(text string) V {
1640
+ s := []rune(text)
1641
+ n := len(s)
1642
+ ws := func(i int) int {
1643
+ for i < n && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r') {
1644
+ i++
1645
+ }
1646
+ return i
1647
+ }
1648
+ fail := func(msg string, pos int) { panic(&jsonError{msg, pos}) }
1649
+ startsWith := func(i int, w string) bool { return i+len(w) <= n && string(s[i:i+len(w)]) == w }
1650
+ isHex := func(i int) bool {
1651
+ if i+4 > n {
1652
+ return false
1653
+ }
1654
+ for _, ch := range s[i : i+4] {
1655
+ if !strings.ContainsRune("0123456789abcdefABCDEF", ch) {
1656
+ return false
1657
+ }
1658
+ }
1659
+ return true
1660
+ }
1661
+ var str func(begin int) (string, int)
1662
+ str = func(begin int) (string, int) {
1663
+ i := begin + 1
1664
+ var b strings.Builder
1665
+ for {
1666
+ if i >= n {
1667
+ fail("Unterminated string starting at", begin)
1668
+ }
1669
+ ch := s[i]
1670
+ if ch == '"' {
1671
+ return b.String(), i + 1
1672
+ }
1673
+ if ch < 0x20 {
1674
+ fail("Invalid control character at", i)
1675
+ }
1676
+ if ch != '\\' {
1677
+ b.WriteRune(ch)
1678
+ i++
1679
+ continue
1680
+ }
1681
+ if i+1 >= n {
1682
+ fail("Unterminated string starting at", begin)
1683
+ }
1684
+ esc := s[i+1]
1685
+ simple := map[rune]string{'"': "\"", '\\': "\\", '/': "/", 'b': "\b", 'f': "\f", 'n': "\n", 'r': "\r", 't': "\t"}
1686
+ if v, ok := simple[esc]; ok {
1687
+ b.WriteString(v)
1688
+ i += 2
1689
+ continue
1690
+ }
1691
+ if esc != 'u' {
1692
+ fail("Invalid \\escape", i)
1693
+ }
1694
+ if !isHex(i + 2) {
1695
+ fail("Invalid \\uXXXX escape", i+1)
1696
+ }
1697
+ cp64, _ := strconv.ParseInt(string(s[i+2:i+6]), 16, 32)
1698
+ cp := rune(cp64)
1699
+ i += 6
1700
+ if cp >= 0xd800 && cp <= 0xdbff && i+1 < n && s[i] == '\\' && s[i+1] == 'u' && isHex(i+2) {
1701
+ lo64, _ := strconv.ParseInt(string(s[i+2:i+6]), 16, 32)
1702
+ lo := rune(lo64)
1703
+ if lo >= 0xdc00 && lo <= 0xdfff {
1704
+ cp = 0x10000 + ((cp - 0xd800) << 10) + (lo - 0xdc00)
1705
+ i += 6
1706
+ }
1707
+ }
1708
+ b.WriteRune(cp)
1709
+ }
1710
+ }
1711
+ var value func(i int) (V, int)
1712
+ number := func(i int) (V, int, bool) {
1713
+ j := i
1714
+ if j < n && s[j] == '-' {
1715
+ j++
1716
+ }
1717
+ if j >= n || s[j] < '0' || s[j] > '9' {
1718
+ return nil, 0, false
1719
+ }
1720
+ if s[j] == '0' {
1721
+ j++
1722
+ } else {
1723
+ for j < n && s[j] >= '0' && s[j] <= '9' {
1724
+ j++
1725
+ }
1726
+ }
1727
+ frac, exp := false, false
1728
+ if j+1 < n && s[j] == '.' && s[j+1] >= '0' && s[j+1] <= '9' {
1729
+ frac = true
1730
+ j++
1731
+ for j < n && s[j] >= '0' && s[j] <= '9' {
1732
+ j++
1733
+ }
1734
+ }
1735
+ if j < n && (s[j] == 'e' || s[j] == 'E') {
1736
+ k := j + 1
1737
+ if k < n && (s[k] == '+' || s[k] == '-') {
1738
+ k++
1739
+ }
1740
+ if k < n && s[k] >= '0' && s[k] <= '9' {
1741
+ exp = true
1742
+ for k < n && s[k] >= '0' && s[k] <= '9' {
1743
+ k++
1744
+ }
1745
+ j = k
1746
+ }
1747
+ }
1748
+ t := string(s[i:j])
1749
+ if frac || exp {
1750
+ return ParseDec(t), j, true
1751
+ }
1752
+ v, _ := new(big.Int).SetString(t, 10)
1753
+ return v, j, true
1754
+ }
1755
+ var obj, arr func(i int) (V, int)
1756
+ value = func(i int) (V, int) {
1757
+ if i >= n {
1758
+ fail("Expecting value", i)
1759
+ }
1760
+ ch := s[i]
1761
+ switch {
1762
+ case ch == '"':
1763
+ v, j := str(i)
1764
+ return v, j
1765
+ case ch == '{':
1766
+ return obj(i + 1)
1767
+ case ch == '[':
1768
+ return arr(i + 1)
1769
+ case startsWith(i, "null"):
1770
+ return nil, i + 4
1771
+ case startsWith(i, "true"):
1772
+ return true, i + 4
1773
+ case startsWith(i, "false"):
1774
+ return false, i + 5
1775
+ }
1776
+ if v, j, ok := number(i); ok {
1777
+ return v, j
1778
+ }
1779
+ fail("Expecting value", i)
1780
+ return nil, 0
1781
+ }
1782
+ obj = func(i int) (V, int) {
1783
+ d := newDict()
1784
+ i = ws(i)
1785
+ if i < n && s[i] == '}' {
1786
+ return d, i + 1
1787
+ }
1788
+ for {
1789
+ if i >= n || s[i] != '"' {
1790
+ fail("Expecting property name enclosed in double quotes", i)
1791
+ }
1792
+ var k string
1793
+ k, i = str(i)
1794
+ i = ws(i)
1795
+ if i >= n || s[i] != ':' {
1796
+ fail("Expecting ':' delimiter", i)
1797
+ }
1798
+ i = ws(i + 1)
1799
+ var v V
1800
+ v, i = value(i)
1801
+ d.set(k, v)
1802
+ i = ws(i)
1803
+ if i < n && s[i] == '}' {
1804
+ return d, i + 1
1805
+ }
1806
+ if i >= n || s[i] != ',' {
1807
+ fail("Expecting ',' delimiter", i)
1808
+ }
1809
+ comma := i
1810
+ i = ws(i + 1)
1811
+ if i < n && s[i] == '}' {
1812
+ fail("Illegal trailing comma before end of object", comma)
1813
+ }
1814
+ }
1815
+ }
1816
+ arr = func(i int) (V, int) {
1817
+ out := []V{}
1818
+ i = ws(i)
1819
+ if i < n && s[i] == ']' {
1820
+ return &List{out}, i + 1
1821
+ }
1822
+ for {
1823
+ var v V
1824
+ v, i = value(i)
1825
+ out = append(out, v)
1826
+ i = ws(i)
1827
+ if i < n && s[i] == ']' {
1828
+ return &List{out}, i + 1
1829
+ }
1830
+ if i >= n || s[i] != ',' {
1831
+ fail("Expecting ',' delimiter", i)
1832
+ }
1833
+ comma := i
1834
+ i = ws(i + 1)
1835
+ if i < n && s[i] == ']' {
1836
+ fail("Illegal trailing comma before end of array", comma)
1837
+ }
1838
+ }
1839
+ }
1840
+ var result V
1841
+ func() {
1842
+ defer func() {
1843
+ if r := recover(); r != nil {
1844
+ je, ok := r.(*jsonError)
1845
+ if !ok {
1846
+ panic(r)
1847
+ }
1848
+ before := s[:je.pos]
1849
+ line := 1
1850
+ last := -1
1851
+ for k, ch := range before {
1852
+ if ch == '\n' {
1853
+ line++
1854
+ last = k
1855
+ }
1856
+ }
1857
+ col := je.pos - last
1858
+ panic(ConversionFailed(fmt.Sprintf("This is not JSON: %s (line %d, column %d).", je.msg, line, col)))
1859
+ }
1860
+ }()
1861
+ v, end := value(ws(0))
1862
+ end = ws(end)
1863
+ if end != n {
1864
+ fail("Extra data", end)
1865
+ }
1866
+ result = v
1867
+ }()
1868
+ return result
1869
+ }
1870
+
1871
+ func jsonReady(v V) V {
1872
+ switch x := v.(type) {
1873
+ case nil, bool, string, *big.Int, *Dec:
1874
+ return v
1875
+ case *Money:
1876
+ panic(KindMismatch("Money has no JSON form of its own: use its amount, for example price's amount."))
1877
+ case *List:
1878
+ out := make([]V, len(x.Items))
1879
+ for i, y := range x.Items {
1880
+ out[i] = jsonReady(y)
1881
+ }
1882
+ return &List{out}
1883
+ case *Tuple:
1884
+ out := make([]V, len(x.Items))
1885
+ for i, y := range x.Items {
1886
+ out[i] = jsonReady(y)
1887
+ }
1888
+ return &List{out}
1889
+ case *Dict:
1890
+ out := newDict()
1891
+ for _, e := range x.entries() {
1892
+ if _, ok := e.k.(string); !ok {
1893
+ panic(KindMismatch("A JSON object's keys are text, but one is " + describe(e.k) + "."))
1894
+ }
1895
+ out.set(e.k, jsonReady(e.v))
1896
+ }
1897
+ return out
1898
+ case *Record:
1899
+ out := newDict()
1900
+ for _, f := range x.Cls.Fields {
1901
+ out.set(f.Py, jsonReady(x.F[f.Py]))
1902
+ }
1903
+ return out
1904
+ }
1905
+ panic(KindMismatch(describe(v) + " has no JSON form."))
1906
+ }
1907
+
1908
+ func jsonStr(s string) string {
1909
+ var b strings.Builder
1910
+ b.WriteByte('"')
1911
+ for _, ch := range s {
1912
+ switch {
1913
+ case ch == '"':
1914
+ b.WriteString("\\\"")
1915
+ case ch == '\\':
1916
+ b.WriteString("\\\\")
1917
+ case ch == '\n':
1918
+ b.WriteString("\\n")
1919
+ case ch == '\r':
1920
+ b.WriteString("\\r")
1921
+ case ch == '\t':
1922
+ b.WriteString("\\t")
1923
+ case ch == '\b':
1924
+ b.WriteString("\\b")
1925
+ case ch == '\f':
1926
+ b.WriteString("\\f")
1927
+ case ch >= 0x20 && ch <= 0x7e:
1928
+ b.WriteRune(ch)
1929
+ case ch > 0xffff:
1930
+ v := ch - 0x10000
1931
+ b.WriteString(fmt.Sprintf("\\u%x\\u%x", 0xd800+(v>>10), 0xdc00+(v&0x3ff)))
1932
+ default:
1933
+ b.WriteString(fmt.Sprintf("\\u%04x", ch))
1934
+ }
1935
+ }
1936
+ b.WriteByte('"')
1937
+ return b.String()
1938
+ }
1939
+
1940
+ func jsonText(v V) string {
1941
+ var w func(x V) string
1942
+ w = func(x V) string {
1943
+ switch y := x.(type) {
1944
+ case nil:
1945
+ return "null"
1946
+ case bool:
1947
+ if y {
1948
+ return "true"
1949
+ }
1950
+ return "false"
1951
+ case *big.Int:
1952
+ return y.String()
1953
+ case *Dec:
1954
+ t := y.String()
1955
+ if y.isIntegral() && strings.Contains(t, "E") {
1956
+ return y.toFixed(-1, false)
1957
+ }
1958
+ return t
1959
+ case string:
1960
+ return jsonStr(y)
1961
+ case *List:
1962
+ parts := make([]string, len(y.Items))
1963
+ for i, z := range y.Items {
1964
+ parts[i] = w(z)
1965
+ }
1966
+ return "[" + strings.Join(parts, ", ") + "]"
1967
+ case *Dict:
1968
+ parts := []string{}
1969
+ for _, e := range y.entries() {
1970
+ parts = append(parts, jsonStr(e.k.(string))+": "+w(e.v))
1971
+ }
1972
+ return "{" + strings.Join(parts, ", ") + "}"
1973
+ }
1974
+ return ""
1975
+ }
1976
+ return w(jsonReady(v))
1977
+ }
1978
+
1979
+ // ── Helpers the generated code calls ───────────────────────────────────────────────────────────────────────────
1980
+
1981
+ const maxFrames = 997 // as deep as the generated Python goes (recursion limit 1000, less its own frames)
1982
+
1983
+ // RangeInt is a whole number for counting (range, repeat).
1984
+ func RangeInt(v V) int64 {
1985
+ switch x := v.(type) {
1986
+ case *big.Int:
1987
+ return x.Int64()
1988
+ case bool:
1989
+ if x {
1990
+ return 1
1991
+ }
1992
+ return 0
1993
+ }
1994
+ name := "object"
1995
+ switch v.(type) {
1996
+ case *Dec:
1997
+ name = "decimal.Decimal"
1998
+ case nil:
1999
+ name = "NoneType"
2000
+ case *Money:
2001
+ name = "Money"
2002
+ case string:
2003
+ name = "str"
2004
+ }
2005
+ panic(TypeErr("'" + name + "' object cannot be interpreted as an integer"))
2006
+ }
2007
+
2008
+ // I is a whole number from a Go number; Int from its digits.
2009
+ func I(n int64) V { return big.NewInt(n) }
2010
+ func Int(digits string) V {
2011
+ v, _ := new(big.Int).SetString(digits, 10)
2012
+ return v
2013
+ }
2014
+
2015
+ // Unpack2 splits a pair into its two values, as Python's `a, b = el` does.
2016
+ func Unpack2(el V) (V, V) {
2017
+ var items []V
2018
+ switch x := el.(type) {
2019
+ case *List:
2020
+ items = x.Items
2021
+ case *Tuple:
2022
+ items = x.Items
2023
+ case string:
2024
+ for _, r := range runes(x) {
2025
+ items = append(items, r)
2026
+ }
2027
+ if items == nil {
2028
+ items = []V{}
2029
+ }
2030
+ case *Dict:
2031
+ items = x.keys()
2032
+ }
2033
+ if items == nil {
2034
+ name := "object"
2035
+ switch el.(type) {
2036
+ case nil:
2037
+ name = "NoneType"
2038
+ case *big.Int:
2039
+ name = "int"
2040
+ case *Dec:
2041
+ name = "decimal.Decimal"
2042
+ case bool:
2043
+ name = "bool"
2044
+ }
2045
+ panic(TypeErr("cannot unpack non-iterable " + name + " object"))
2046
+ }
2047
+ if len(items) < 2 {
2048
+ panic(PyErr("ValueError", fmt.Sprintf("not enough values to unpack (expected 2, got %d)", len(items))))
2049
+ }
2050
+ if len(items) > 2 {
2051
+ panic(PyErr("ValueError", fmt.Sprintf("too many values to unpack (expected 2, got %d)", len(items))))
2052
+ }
2053
+ return items[0], items[1]
2054
+ }
2055
+
2056
+ func MapItems(m V) V {
2057
+ d, ok := m.(*Dict)
2058
+ if !ok {
2059
+ panic(attrErr(m, "items"))
2060
+ }
2061
+ return &List{d.items()}
2062
+ }
2063
+ func PairsOf(c V) V {
2064
+ if d, ok := c.(*Dict); ok {
2065
+ return &List{d.items()}
2066
+ }
2067
+ return PyList(c)
2068
+ }
2069
+
2070
+ func plural(n int) string {
2071
+ if n == 1 {
2072
+ return ""
2073
+ }
2074
+ return "s"
2075
+ }
2076
+
2077
+ // ItemAt is "list at position": positions start at 1. dflt (optional) is given back when there is no such item.
2078
+ func ItemAt(items V, position V, dflt ...V) V {
2079
+ p, ok := position.(*big.Int)
2080
+ if !ok {
2081
+ panic(KindMismatch("A position in a list is a whole number, not " + describe(position) + "."))
2082
+ }
2083
+ var list []V
2084
+ switch x := items.(type) {
2085
+ case *List:
2086
+ list = x.Items
2087
+ case *Tuple:
2088
+ list = x.Items
2089
+ default:
2090
+ name := "object"
2091
+ if items == nil {
2092
+ name = "NoneType"
2093
+ }
2094
+ panic(TypeErr("object of type '" + name + "' has no len()"))
2095
+ }
2096
+ if p.Cmp(bigOne) >= 0 && p.Cmp(big.NewInt(int64(len(list)))) <= 0 {
2097
+ return list[p.Int64()-1]
2098
+ }
2099
+ if len(dflt) > 0 {
2100
+ return dflt[0]
2101
+ }
2102
+ panic(MissingValue(fmt.Sprintf("There is no item %s: the list has %d item%s.", p.String(), len(list), plural(len(list)))))
2103
+ }
2104
+
2105
+ func SetItem(items V, position V, value V) {
2106
+ ItemAt(items, position)
2107
+ items.(*List).Items[position.(*big.Int).Int64()-1] = value
2108
+ }
2109
+
2110
+ func MapSet(m, k, v V) {
2111
+ switch x := m.(type) {
2112
+ case *Dict:
2113
+ x.set(k, v)
2114
+ return
2115
+ case nil:
2116
+ panic(TypeErr("'NoneType' object does not support item assignment"))
2117
+ case *List:
2118
+ SetItem(x, k, v)
2119
+ return
2120
+ case *Money:
2121
+ panic(TypeErr("'Money' object does not support item assignment"))
2122
+ }
2123
+ panic(TypeErr("'object' object does not support item assignment"))
2124
+ }
2125
+
2126
+ func SetEntry(c, k, v V) {
2127
+ switch x := c.(type) {
2128
+ case *List:
2129
+ SetItem(x, k, v)
2130
+ case *Dict:
2131
+ x.set(k, v)
2132
+ case nil:
2133
+ panic(MissingValue("This value is nothing, so it has no entry for " + Show(k) + "."))
2134
+ default:
2135
+ panic(KindMismatch(describe(c) + " has no entries that can be changed."))
2136
+ }
2137
+ }
2138
+
2139
+ func Entry(c, k V, dflt ...V) V {
2140
+ switch x := c.(type) {
2141
+ case *List, *Tuple:
2142
+ return ItemAt(c, k, dflt...)
2143
+ case *Dict:
2144
+ if v, ok := x.get(k); ok {
2145
+ return v
2146
+ }
2147
+ if len(dflt) > 0 {
2148
+ return dflt[0]
2149
+ }
2150
+ panic(MissingValue("There is no entry for " + Show(k) + "."))
2151
+ case nil:
2152
+ panic(MissingValue("This value is nothing, so it has no entry for " + Show(k) + "."))
2153
+ }
2154
+ panic(KindMismatch(describe(c) + " has no entries."))
2155
+ }
2156
+
2157
+ func MapGet(m, k V, dflt ...V) V {
2158
+ switch x := m.(type) {
2159
+ case *Dict:
2160
+ if v, ok := x.get(k); ok {
2161
+ return v
2162
+ }
2163
+ if len(dflt) > 0 {
2164
+ return dflt[0]
2165
+ }
2166
+ panic(&Err{PyType: "KeyError", Message: PyStr(k), Args: []V{k}})
2167
+ case nil:
2168
+ if len(dflt) > 0 {
2169
+ panic(attrErr(m, "get"))
2170
+ }
2171
+ panic(TypeErr("'NoneType' object is not subscriptable"))
2172
+ }
2173
+ if len(dflt) > 0 {
2174
+ panic(attrErr(m, "get"))
2175
+ }
2176
+ if l, ok := m.(*List); ok {
2177
+ if i, ok := k.(*big.Int); ok {
2178
+ n := int64(len(l.Items))
2179
+ iv := i.Int64()
2180
+ if i.IsInt64() && iv >= -n && iv < n {
2181
+ if iv < 0 {
2182
+ iv += n
2183
+ }
2184
+ return l.Items[iv]
2185
+ }
2186
+ }
2187
+ panic(PyErr("IndexError", "list index out of range"))
2188
+ }
2189
+ if _, ok := m.(*Money); ok {
2190
+ panic(TypeErr("'Money' object is not subscriptable"))
2191
+ }
2192
+ panic(TypeErr("'object' object is not subscriptable"))
2193
+ }
2194
+
2195
+ // GetAttr is obj.name for a record field (a Python attribute), or Money's amount.
2196
+ func GetAttr(obj V, name string) V {
2197
+ if r, ok := obj.(*Record); ok {
2198
+ if v, ok := r.F[name]; ok {
2199
+ return v
2200
+ }
2201
+ }
2202
+ if m, ok := obj.(*Money); ok && name == "amount" {
2203
+ return m.Amount
2204
+ }
2205
+ panic(attrErr(obj, name))
2206
+ }
2207
+
2208
+ func fieldNames(key string) []string {
2209
+ lower := strings.ToLower(key)
2210
+ return []string{key, strings.ReplaceAll(key, " ", "_"), lower, strings.ReplaceAll(lower, " ", "_")}
2211
+ }
2212
+
2213
+ func GetField(obj V, key string) V {
2214
+ if obj == nil {
2215
+ panic(MissingValue("This value is nothing, so it has no " + key + "."))
2216
+ }
2217
+ names := fieldNames(key)
2218
+ if d, ok := obj.(*Dict); ok {
2219
+ for _, k := range names {
2220
+ if v, ok := d.get(k); ok {
2221
+ return v
2222
+ }
2223
+ }
2224
+ for _, e := range d.entries() {
2225
+ if strings.ToLower(pyStrip(PyStr(e.k))) == strings.ToLower(key) {
2226
+ return e.v
2227
+ }
2228
+ }
2229
+ ks := []string{}
2230
+ for _, k := range d.keys() {
2231
+ ks = append(ks, PyStr(k))
2232
+ }
2233
+ panic(MissingValue("There is no field \"" + key + "\". Fields here: " + strings.Join(ks, ", ") + "."))
2234
+ }
2235
+ for _, k := range names {
2236
+ if r, ok := obj.(*Record); ok {
2237
+ if v, ok := r.F[k]; ok {
2238
+ return v
2239
+ }
2240
+ }
2241
+ if m, ok := obj.(*Money); ok && k == "amount" {
2242
+ return m.Amount
2243
+ }
2244
+ }
2245
+ panic(MissingValue(describe(obj) + " has no field \"" + key + "\"."))
2246
+ }
2247
+
2248
+ // SetAttr is obj.name = value: a record's Never rules run first, as its __setattr__ does.
2249
+ func SetAttr(obj V, name string, value V) {
2250
+ if r, ok := obj.(*Record); ok {
2251
+ for _, rule := range r.Cls.Rules[name] {
2252
+ Never(rule.Cond(value), rule.Text, rule.Line, value)
2253
+ }
2254
+ r.F[name] = value
2255
+ return
2256
+ }
2257
+ if _, ok := obj.(*Money); ok {
2258
+ panic(PyErr("AttributeError", "Money cannot be changed; make new money instead."))
2259
+ }
2260
+ panic(attrErr(obj, name))
2261
+ }
2262
+
2263
+ func SetField(obj V, key string, value V) {
2264
+ if d, ok := obj.(*Dict); ok {
2265
+ d.set(key, value)
2266
+ return
2267
+ }
2268
+ for _, k := range fieldNames(key) {
2269
+ if r, ok := obj.(*Record); ok {
2270
+ if _, has := r.F[k]; has {
2271
+ SetAttr(obj, k, value)
2272
+ return
2273
+ }
2274
+ }
2275
+ }
2276
+ panic(MissingValue(describe(obj) + " has no field \"" + key + "\"."))
2277
+ }
2278
+
2279
+ func AddTo(target, value V) V {
2280
+ if l, ok := target.(*List); ok {
2281
+ l.Items = append(l.Items, value)
2282
+ return l
2283
+ }
2284
+ return Add(target, value)
2285
+ }
2286
+ func AppendTo(target, value V) {
2287
+ l, ok := target.(*List)
2288
+ if !ok {
2289
+ panic(attrErr(target, "append"))
2290
+ }
2291
+ l.Items = append(l.Items, value)
2292
+ }
2293
+ func RemoveFrom(target, value V) {
2294
+ if d, ok := target.(*Dict); ok {
2295
+ if !d.has(value) {
2296
+ panic(MissingValue("There is no entry for " + Show(value) + " to remove."))
2297
+ }
2298
+ d.del(value)
2299
+ return
2300
+ }
2301
+ if !contains(target, value) {
2302
+ panic(MissingValue(Show(value) + " is not in the list, so it can't be removed."))
2303
+ }
2304
+ l, ok := target.(*List)
2305
+ if !ok {
2306
+ panic(attrErr(target, "remove"))
2307
+ }
2308
+ for i, x := range l.Items {
2309
+ if sameRef(x, value) || Eq(x, value) {
2310
+ l.Items = append(l.Items[:i:i], l.Items[i+1:]...)
2311
+ return
2312
+ }
2313
+ }
2314
+ }
2315
+ func SortInPlace(target V, key func(V) V, desc bool) {
2316
+ l, ok := target.(*List)
2317
+ if !ok {
2318
+ panic(attrErr(target, "sort"))
2319
+ }
2320
+ l.Items = pySort(l.Items, key, desc)
2321
+ }
2322
+ func ReverseInPlace(target V) {
2323
+ l, ok := target.(*List)
2324
+ if !ok {
2325
+ panic(attrErr(target, "reverse"))
2326
+ }
2327
+ for i, j := 0, len(l.Items)-1; i < j; i, j = i+1, j-1 {
2328
+ l.Items[i], l.Items[j] = l.Items[j], l.Items[i]
2329
+ }
2330
+ }
2331
+
2332
+ // Kind makes a kind of record.
2333
+ func Kind(py string, fields []Field, rules map[string][]Rule) *RecordKind {
2334
+ if rules == nil {
2335
+ rules = map[string][]Rule{}
2336
+ }
2337
+ return &RecordKind{py, fields, rules}
2338
+ }
2339
+
2340
+ // Pair is a field given when a record is made.
2341
+ type Pair struct {
2342
+ Py string
2343
+ V V
2344
+ }
2345
+
2346
+ // NewRecord makes a record: the fields it is given, the others defaulted; each set through its Never rules.
2347
+ func NewRecord(cls *RecordKind, given ...Pair) V {
2348
+ g := map[string]V{}
2349
+ for _, p := range given {
2350
+ g[p.Py] = p.V
2351
+ }
2352
+ missing := []string{}
2353
+ for _, f := range cls.Fields {
2354
+ if _, ok := g[f.Py]; !ok && f.Kind != "optional" && f.Kind != "list" && f.Kind != "map" {
2355
+ missing = append(missing, "'"+f.Py+"'")
2356
+ }
2357
+ }
2358
+ if len(missing) > 0 {
2359
+ sep := ", "
2360
+ if len(missing) == 2 {
2361
+ sep = " and "
2362
+ }
2363
+ panic(TypeErr(fmt.Sprintf("%s.__init__() missing %d required keyword-only argument%s: %s", cls.Py, len(missing), plural(len(missing)), strings.Join(missing, sep))))
2364
+ }
2365
+ rec := &Record{cls, map[string]V{}}
2366
+ for _, f := range cls.Fields {
2367
+ v, ok := g[f.Py]
2368
+ if !ok {
2369
+ switch f.Kind {
2370
+ case "optional":
2371
+ v = nil
2372
+ case "list":
2373
+ v = &List{[]V{}}
2374
+ default:
2375
+ v = newDict()
2376
+ }
2377
+ }
2378
+ SetAttr(rec, f.Py, v)
2379
+ }
2380
+ return rec
2381
+ }
2382
+
2383
+ // Never is never(cond, text, rule, value): a broken Never rule stops the program.
2384
+ func Never(cond V, text string, line int, value V) {
2385
+ if Truthy(cond) {
2386
+ panic(RuleBroken(fmt.Sprintf("%s (the rule on line %d), but the value is %s.", text, line, Show(value))))
2387
+ }
2388
+ }
2389
+
2390
+ // ApplyOp is an operation written as words: the sum of, the first of, the words of, ...
2391
+ func ApplyOp(op string, a V) V {
2392
+ switch op {
2393
+ case "sum":
2394
+ return totalOf(iterItems(a))
2395
+ case "average":
2396
+ items := iterItems(a)
2397
+ if len(items) == 0 {
2398
+ panic(MissingValue("I can't take the average of an empty list."))
2399
+ }
2400
+ return Divide(totalOf(items), big.NewInt(int64(len(items))))
2401
+ case "count", "length":
2402
+ return PyLen(a)
2403
+ case "min", "max":
2404
+ items := iterItems(a)
2405
+ if len(items) == 0 {
2406
+ if op == "min" {
2407
+ panic(MissingValue("An empty list has no smallest item."))
2408
+ }
2409
+ panic(MissingValue("An empty list has no largest item."))
2410
+ }
2411
+ best := items[0]
2412
+ cmp := "<"
2413
+ if op == "max" {
2414
+ cmp = ">"
2415
+ }
2416
+ for _, x := range items[1:] {
2417
+ if Compare(cmp, x, best) {
2418
+ best = x
2419
+ }
2420
+ }
2421
+ return best
2422
+ case "first", "last":
2423
+ items := iterItems(a)
2424
+ if len(items) == 0 {
2425
+ panic(MissingValue("An empty list has no " + op + " item."))
2426
+ }
2427
+ if op == "first" {
2428
+ return items[0]
2429
+ }
2430
+ return items[len(items)-1]
2431
+ case "words":
2432
+ out := []V{}
2433
+ for _, p := range pySplit(PyStr(a)) {
2434
+ if w := stripPunct(p.(string)); w != "" {
2435
+ out = append(out, w)
2436
+ }
2437
+ }
2438
+ return &List{out}
2439
+ case "lines":
2440
+ return &List{splitLines(strMethod(a, "splitlines"))}
2441
+ case "lowercase":
2442
+ return pyLower(strMethod(a, "lower"))
2443
+ case "uppercase":
2444
+ return pyUpper(strMethod(a, "upper"))
2445
+ case "trimmed":
2446
+ return pyStrip(strMethod(a, "strip"))
2447
+ case "parts":
2448
+ return &List{pySplit(textOf(a, "\"the parts of\""))}
2449
+ case "abs":
2450
+ if m, ok := a.(*Money); ok {
2451
+ return &Money{m.Amount.abs()}
2452
+ }
2453
+ if _, ok := a.(bool); ok || !isNumber(a) {
2454
+ panic(KindMismatch("\"the absolute value of\" needs a number or money, but it is " + describe(a) + "."))
2455
+ }
2456
+ if n, ok := a.(*big.Int); ok {
2457
+ return new(big.Int).Abs(n)
2458
+ }
2459
+ return a.(*Dec).abs()
2460
+ case "jsonText":
2461
+ return jsonText(a)
2462
+ case "jsonData":
2463
+ return jsonParse(textOf(a, "\"the JSON data in\""))
2464
+ case "keys":
2465
+ d, ok := a.(*Dict)
2466
+ if !ok {
2467
+ panic(attrErr(a, "keys"))
2468
+ }
2469
+ return &List{d.keys()}
2470
+ case "values":
2471
+ d, ok := a.(*Dict)
2472
+ if !ok {
2473
+ panic(attrErr(a, "values"))
2474
+ }
2475
+ return &List{d.values()}
2476
+ }
2477
+ panic(PyErr("NameError", "name '"+op+"' is not defined"))
2478
+ }
2479
+
2480
+ // pyLower / pyUpper: Unicode case mapping, with the special cases JavaScript and Python share.
2481
+ func pyLower(s string) string {
2482
+ var b strings.Builder
2483
+ for _, r := range s {
2484
+ if r == 'İ' {
2485
+ b.WriteString("i̇")
2486
+ continue
2487
+ }
2488
+ b.WriteRune(unicode.ToLower(r))
2489
+ }
2490
+ return b.String()
2491
+ }
2492
+ func pyUpper(s string) string {
2493
+ var b strings.Builder
2494
+ for _, r := range s {
2495
+ switch r {
2496
+ case 'ß':
2497
+ b.WriteString("SS")
2498
+ case 'ʼn':
2499
+ b.WriteString("ʼN")
2500
+ case 'ff':
2501
+ b.WriteString("FF")
2502
+ case 'fi':
2503
+ b.WriteString("FI")
2504
+ case 'fl':
2505
+ b.WriteString("FL")
2506
+ default:
2507
+ b.WriteRune(unicode.ToUpper(r))
2508
+ }
2509
+ }
2510
+ return b.String()
2511
+ }
2512
+
2513
+ // Affix is "starts with" / "ends with": both sides must be text.
2514
+ func Affix(t, a V, end bool) bool {
2515
+ what := "\"starts with\""
2516
+ if end {
2517
+ what = "\"ends with\""
2518
+ }
2519
+ ts := textOf(t, what)
2520
+ as := textOf(a, what)
2521
+ if end {
2522
+ return strings.HasSuffix(ts, as)
2523
+ }
2524
+ return strings.HasPrefix(ts, as)
2525
+ }
2526
+
2527
+ // Between is lo <= v <= hi, the way Python chains it: hi is worked out only when the first part holds.
2528
+ func Between(lo, v V, hi func() V) bool {
2529
+ if !Compare("<=", lo, v) {
2530
+ return false
2531
+ }
2532
+ return Compare("<=", v, hi())
2533
+ }
2534
+
2535
+ // IsIn is `item in container`, with the item worked out first (as Python does).
2536
+ func IsIn(item, container V) bool { return contains(container, item) }
2537
+
2538
+ // ReadText reads a file the program names, from the folder it runs in.
2539
+ func ReadText(path V) V {
2540
+ p, ok := path.(string)
2541
+ if !ok {
2542
+ name := "object"
2543
+ if path == nil {
2544
+ name = "NoneType"
2545
+ }
2546
+ panic(TypeErr("expected str, bytes or os.PathLike object, not " + name))
2547
+ }
2548
+ wd, _ := os.Getwd()
2549
+ full := p
2550
+ if !filepath.IsAbs(p) {
2551
+ full = filepath.Join(wd, p)
2552
+ }
2553
+ st, err := os.Stat(full)
2554
+ if err != nil {
2555
+ if os.IsNotExist(err) {
2556
+ panic(MissingValue("There is no file \"" + p + "\" (looked in the folder the program runs in)."))
2557
+ }
2558
+ panic(PyErr("OSError", err.Error()))
2559
+ }
2560
+ if st.IsDir() {
2561
+ panic(PyErr("IsADirectoryError", "EISDIR: illegal operation on a directory, read"))
2562
+ }
2563
+ data, err := os.ReadFile(full)
2564
+ if err != nil {
2565
+ panic(PyErr("OSError", err.Error()))
2566
+ }
2567
+ return string(data)
2568
+ }
2569
+
2570
+ // Try runs `run`; a Thunder or Python error it raises is given back (anything else goes on).
2571
+ func Try(run func()) (failure *Err) {
2572
+ defer func() {
2573
+ if r := recover(); r != nil {
2574
+ failure = AsPyErr(r)
2575
+ }
2576
+ }()
2577
+ run()
2578
+ return nil
2579
+ }
2580
+
2581
+ // ExpectTrue / ExpectFailure / ExpectValue: the checks, the way thunder_runtime.py's expect_* do them.
2582
+ func ExpectTrue(v V, text string) {
2583
+ if b, ok := v.(bool); !ok || !b {
2584
+ panic(ExpectationFailed(text + ", but it was not true."))
2585
+ }
2586
+ }
2587
+
2588
+ func ExpectFailure(run func(), text string, msg V) {
2589
+ if err := Try(run); err != nil {
2590
+ if err.Thunder && msg != nil {
2591
+ m, ok := msg.(string)
2592
+ if !ok {
2593
+ name := "object"
2594
+ if isInt(msg) {
2595
+ name = "int"
2596
+ }
2597
+ panic(TypeErr("'in <string>' requires string as left operand, not " + name))
2598
+ }
2599
+ if !strings.Contains(err.Message, m) {
2600
+ panic(ExpectationFailed(text + ", but it failed with \"" + err.Message + "\"."))
2601
+ }
2602
+ }
2603
+ return
2604
+ }
2605
+ panic(ExpectationFailed(text + ", but it did not fail."))
2606
+ }
2607
+
2608
+ var checks = map[string]func(a, b V) bool{
2609
+ "is": func(a, b V) bool { return Eq(a, b) },
2610
+ "is not": func(a, b V) bool { return !Eq(a, b) },
2611
+ "at least": func(a, b V) bool { return Compare(">=", a, b) },
2612
+ "at most": func(a, b V) bool { return Compare("<=", a, b) },
2613
+ "more than": func(a, b V) bool { return Compare(">", a, b) },
2614
+ "less than": func(a, b V) bool { return Compare("<", a, b) },
2615
+ "nothing": func(a, b V) bool { return a == nil },
2616
+ "not nothing": func(a, b V) bool { return a != nil },
2617
+ "empty": func(a, b V) bool { return Eq(PyLen(a), bigZero) },
2618
+ "positive": func(a, b V) bool { return Compare(">", a, bigZero) },
2619
+ "negative": func(a, b V) bool { return Compare("<", a, bigZero) },
2620
+ "zero": func(a, b V) bool { return Eq(a, bigZero) },
2621
+ "between": func(a, b V) bool {
2622
+ lh := b.(*List).Items
2623
+ return Compare("<=", lh[0], a) && Compare("<=", a, lh[1])
2624
+ },
2625
+ "in": func(a, b V) bool { return contains(b, a) },
2626
+ "contains": func(a, b V) bool { return contains(a, b) },
2627
+ }
2628
+
2629
+ func ExpectValue(actual V, full, op string, want V, text string) {
2630
+ var ok bool
2631
+ if known, has := checks[full]; has {
2632
+ ok = known(actual, want)
2633
+ } else {
2634
+ ok = !checks[op](actual, want)
2635
+ }
2636
+ if !ok {
2637
+ panic(ExpectationFailed(text + ", but it was " + Show(actual) + "."))
2638
+ }
2639
+ }
2640
+
2641
+ func describeError(e *Err) string {
2642
+ where := e.Where
2643
+ message := Explain(e)
2644
+ code := codeOf(e)
2645
+ if code == "TC508" && !e.Thunder {
2646
+ message = "Python code used by this line failed: " + message
2647
+ }
2648
+ place := "In the program"
2649
+ if len(where) > 0 {
2650
+ inner := where[len(where)-1]
2651
+ place = fmt.Sprintf("%s, line %d", inner.File, inner.Line)
2652
+ if len(where) > 1 {
2653
+ callers := []string{}
2654
+ for i := len(where) - 2; i >= 0; i-- {
2655
+ callers = append(callers, strconv.Itoa(where[i].Line))
2656
+ }
2657
+ place += " (reached from line " + strings.Join(callers, ", then line ") + ")"
2658
+ }
2659
+ }
2660
+ return place + ": " + message + " [" + code + "]"
2661
+ }
2662
+
2663
+ // Values the generated code writes literally.
2664
+ func D(text string) V { return ParseDec(text) }
2665
+ func M(text string) V { return moneyOf(text) }
2666
+ func Today() V { t := time.Now(); return &Date{t.Year(), int(t.Month()), t.Day()} }
2667
+ func DateOf(text string) V {
2668
+ d := parseDate(text)
2669
+ if d == nil {
2670
+ panic(PyErr("ValueError", "Invalid isoformat string: '"+text+"'"))
2671
+ }
2672
+ return d
2673
+ }
2674
+
2675
+ func isNumberText(s string) bool {
2676
+ if s == "" {
2677
+ return false
2678
+ }
2679
+ i := 0
2680
+ if s[0] == '+' || s[0] == '-' {
2681
+ i = 1
2682
+ }
2683
+ if i >= len(s) || s[i] < '0' || s[i] > '9' {
2684
+ return false
2685
+ }
2686
+ for i < len(s) && ((s[i] >= '0' && s[i] <= '9') || s[i] == '_') {
2687
+ i++
2688
+ }
2689
+ if i == len(s) {
2690
+ return true
2691
+ }
2692
+ if s[i] != '.' || i+1 >= len(s) {
2693
+ return false
2694
+ }
2695
+ i++
2696
+ for i < len(s) {
2697
+ if s[i] < '0' || s[i] > '9' {
2698
+ return false
2699
+ }
2700
+ i++
2701
+ }
2702
+ return true
2703
+ }
2704
+
2705
+ func ToNumber(x V) V {
2706
+ if isNumber(x) {
2707
+ return x
2708
+ }
2709
+ if m, ok := x.(*Money); ok {
2710
+ return m.Amount
2711
+ }
2712
+ if s, ok := x.(string); ok {
2713
+ t := strings.ReplaceAll(pyStrip(s), ",", "")
2714
+ if isNumberText(t) {
2715
+ if strings.Contains(t, ".") {
2716
+ return ParseDec(t)
2717
+ }
2718
+ v, _ := new(big.Int).SetString(strings.ReplaceAll(strings.TrimPrefix(t, "+"), "_", ""), 10)
2719
+ return v
2720
+ }
2721
+ }
2722
+ panic(ConversionFailed(describe(x) + " is not a number."))
2723
+ }
2724
+
2725
+ func ToWhole(x V) V {
2726
+ n := ToNumber(x)
2727
+ if i, ok := n.(*big.Int); ok {
2728
+ return i
2729
+ }
2730
+ d := n.(*Dec)
2731
+ if d.isIntegral() {
2732
+ return d.toBigInt()
2733
+ }
2734
+ panic(ConversionFailed(Show(d) + " is not a whole number."))
2735
+ }
2736
+
2737
+ func ToMoney(x V) V {
2738
+ if m, ok := x.(*Money); ok {
2739
+ return m
2740
+ }
2741
+ if s, ok := x.(string); ok {
2742
+ t := strings.ReplaceAll(pyStrip(s), ",", "")
2743
+ negative := strings.HasPrefix(t, "-")
2744
+ t = strings.TrimLeft(t, "-")
2745
+ t = strings.TrimLeft(t, "$")
2746
+ if isNumberText(t) {
2747
+ if negative {
2748
+ t = "-" + t
2749
+ }
2750
+ return moneyOf(t)
2751
+ }
2752
+ panic(ConversionFailed(describe(x) + " is not an amount of money."))
2753
+ }
2754
+ return &Money{toDec(ToNumber(x))}
2755
+ }
2756
+
2757
+ func ToYesNo(x V) V {
2758
+ if b, ok := x.(bool); ok {
2759
+ return b
2760
+ }
2761
+ if s, ok := x.(string); ok {
2762
+ t := strings.ToLower(pyStrip(s))
2763
+ if t == "yes" || t == "true" {
2764
+ return true
2765
+ }
2766
+ if t == "no" || t == "false" {
2767
+ return false
2768
+ }
2769
+ }
2770
+ panic(ConversionFailed(describe(x) + " is not yes or no."))
2771
+ }
2772
+
2773
+ func ToDate(x V) V {
2774
+ if d, ok := x.(*Date); ok {
2775
+ return d
2776
+ }
2777
+ if d := parseDate(pyStrip(PyStr(x))); d != nil {
2778
+ return d
2779
+ }
2780
+ panic(ConversionFailed(describe(x) + " is not a date (write it as YYYY-MM-DD)."))
2781
+ }
2782
+
2783
+ func totalOf(items []V) V {
2784
+ if len(items) == 0 {
2785
+ return big.NewInt(0)
2786
+ }
2787
+ result := items[0]
2788
+ for _, x := range items[1:] {
2789
+ result = Add(result, x)
2790
+ }
2791
+ return result
2792
+ }
2793
+
2794
+ func textOf(v V, what string) string {
2795
+ s, ok := v.(string)
2796
+ if !ok {
2797
+ panic(KindMismatch(what + " needs text, but it is " + describe(v) + "."))
2798
+ }
2799
+ return s
2800
+ }
2801
+
2802
+ func Joined(items, sep V) V {
2803
+ sp := textOf(sep, "\"joined with\"")
2804
+ out := []string{}
2805
+ for i, x := range iterItems(items) {
2806
+ s, ok := x.(string)
2807
+ if !ok {
2808
+ panic(KindMismatch(fmt.Sprintf("\"joined with\" joins text, but item %d is %s. Turn it into text first.", i+1, describe(x))))
2809
+ }
2810
+ out = append(out, s)
2811
+ }
2812
+ return strings.Join(out, sp)
2813
+ }
2814
+
2815
+ func SplitAt(text, sep V) V {
2816
+ sp := textOf(sep, "\"split at\"")
2817
+ if sp == "" {
2818
+ panic(KindMismatch("\"split at\" needs something to split at, not empty text."))
2819
+ }
2820
+ parts := strings.Split(textOf(text, "\"split at\""), sp)
2821
+ out := make([]V, len(parts))
2822
+ for i, p := range parts {
2823
+ out[i] = p
2824
+ }
2825
+ return &List{out}
2826
+ }
2827
+
2828
+ func Replacing(text, old, nw V) V {
2829
+ o := textOf(old, "\"replacing\"")
2830
+ if o == "" {
2831
+ panic(KindMismatch("\"replacing\" needs something to replace, not empty text."))
2832
+ }
2833
+ t := textOf(text, "\"replacing\"")
2834
+ return strings.ReplaceAll(t, o, textOf(nw, "\"replacing … with\""))
2835
+ }
2836
+
2837
+ const punct = ".,;:!?\"'()[]{}<>“”‘’…-"
2838
+
2839
+ func stripPunct(w string) string {
2840
+ rs := []rune(w)
2841
+ i, j := 0, len(rs)
2842
+ for i < j && strings.ContainsRune(punct, rs[i]) {
2843
+ i++
2844
+ }
2845
+ for j > i && strings.ContainsRune(punct, rs[j-1]) {
2846
+ j--
2847
+ }
2848
+ return string(rs[i:j])
2849
+ }
2850
+
2851
+ // Filter / Pick: "where" and "from" over a list (items read as Python's comprehension does).
2852
+ func Filter(list V, keep func(item V) bool) V {
2853
+ out := []V{}
2854
+ for _, x := range iterItems(list) {
2855
+ if keep(x) {
2856
+ out = append(out, x)
2857
+ }
2858
+ }
2859
+ return &List{out}
2860
+ }
2861
+ func Pick(list V, get func(item V) V) V {
2862
+ items := iterItems(list)
2863
+ out := make([]V, len(items))
2864
+ for i, x := range items {
2865
+ out[i] = get(x)
2866
+ }
2867
+ return &List{out}
2868
+ }
2869
+
2870
+ // EntryAt is one item of a map's entry (0: the key, 1: the value), for sorting a map.
2871
+ func EntryAt(entry V, k int) V { return entry.(*Tuple).Items[k] }
2872
+
2873
+ // Cmp / IsNothing / Not / And: small helpers for the generated conditions.
2874
+ func Cmp(op string, a, b V) V { return Compare(op, a, b) }
2875
+ func IsNothing(v V) bool { return v == nil }
2876
+ func EqLen0(v V) V { return Eq(PyLen(v), bigZero) }
2877
+
2878
+ // ── Running: frames (for error lines), output, and the program or its tests ────────────────────────────────────
2879
+
2880
+ // Frame is where a program, test, call, or kept value is running: its Thunder file and current line.
2881
+ type Frame struct {
2882
+ File string
2883
+ Line int
2884
+ }
2885
+
2886
+ var frames []*Frame
2887
+ var aborted bool
2888
+ var exitCode int
2889
+ var out = bufio.NewWriterSize(os.Stdout, 1<<16)
2890
+
2891
+ func snapshot() []Place {
2892
+ p := make([]Place, len(frames))
2893
+ for i, f := range frames {
2894
+ p[i] = Place{f.File, f.Line}
2895
+ }
2896
+ return p
2897
+ }
2898
+
2899
+ // EnterFrame is a frame for a program, a test, or a kept value.
2900
+ func EnterFrame(file string, line int) *Frame {
2901
+ if len(frames) >= maxFrames {
2902
+ panic(PyErr("RecursionError", "maximum recursion depth exceeded"))
2903
+ }
2904
+ f := &Frame{file, line}
2905
+ frames = append(frames, f)
2906
+ return f
2907
+ }
2908
+
2909
+ // EnterCall is a frame for a call; first is the Thunder line the function starts on (0: none).
2910
+ func EnterCall(file string, line int, first int) *Frame {
2911
+ if len(frames) >= maxFrames {
2912
+ err := PyErr("RecursionError", "maximum recursion depth exceeded")
2913
+ if first != 0 {
2914
+ err.Where = append(snapshot(), Place{file, first})
2915
+ }
2916
+ panic(err)
2917
+ }
2918
+ f := &Frame{file, line}
2919
+ frames = append(frames, f)
2920
+ return f
2921
+ }
2922
+
2923
+ // Exit leaves the innermost frame. Called as `defer func() { T.Exit(recover()) }()`: an error on its way out
2924
+ // remembers where it happened (the innermost frames first seen) and goes on.
2925
+ func Exit(r V) {
2926
+ if r != nil {
2927
+ err := AsPyErr(r)
2928
+ if err.Where == nil {
2929
+ err.Where = snapshot()
2930
+ }
2931
+ frames = frames[:len(frames)-1]
2932
+ panic(err)
2933
+ }
2934
+ frames = frames[:len(frames)-1]
2935
+ }
2936
+
2937
+ // TopFrame is the innermost frame (a record's Never rule runs in its caller's frame).
2938
+ func TopFrame() *Frame { return frames[len(frames)-1] }
2939
+
2940
+ func withFrame(frame *Frame, fn func() V) (v V) {
2941
+ if len(frames) >= maxFrames {
2942
+ panic(PyErr("RecursionError", "maximum recursion depth exceeded"))
2943
+ }
2944
+ frames = append(frames, frame)
2945
+ defer func() { Exit(recover()) }()
2946
+ return fn()
2947
+ }
2948
+
2949
+ // KeyAt is a key for sorting by a field: it runs in a frame at the sorting line, as the generated Python's lambda does.
2950
+ func KeyAt(F *Frame, get func(item V) V) func(V) V {
2951
+ frame := &Frame{F.File, F.Line}
2952
+ return func(item V) V { return withFrame(&Frame{frame.File, frame.Line}, func() V { return get(item) }) }
2953
+ }
2954
+
2955
+ // Say writes a line.
2956
+ func Say(text string) { out.WriteString(text); out.WriteByte('\n') }
2957
+
2958
+ func report(r V) {
2959
+ out.Flush()
2960
+ fmt.Fprintln(os.Stderr, describeError(AsPyErr(r)))
2961
+ exitCode = 1
2962
+ aborted = true
2963
+ }
2964
+
2965
+ // Init works out a file's kept values; an error stops the program with a Thunder message.
2966
+ func Init(file string, fn func(F *Frame)) {
2967
+ if aborted {
2968
+ return
2969
+ }
2970
+ F := &Frame{file, 0}
2971
+ func() {
2972
+ defer func() {
2973
+ if r := recover(); r != nil {
2974
+ report(r)
2975
+ }
2976
+ }()
2977
+ withFrame(F, func() V { fn(F); return nil })
2978
+ }()
2979
+ }
2980
+
2981
+ // Run runs a program's main part, then ends the process with Python's exit status.
2982
+ func Run(main func()) {
2983
+ if !aborted {
2984
+ func() {
2985
+ defer func() {
2986
+ if r := recover(); r != nil {
2987
+ report(r)
2988
+ }
2989
+ }()
2990
+ main()
2991
+ }()
2992
+ }
2993
+ out.Flush()
2994
+ os.Exit(exitCode)
2995
+ }
2996
+
2997
+ // Test is one Test block: its title, its code, and its line.
2998
+ type Test struct {
2999
+ Title string
3000
+ Run func()
3001
+ Line int
3002
+ }
3003
+
3004
+ // Suite is a file's Test blocks.
3005
+ type Suite struct {
3006
+ File string
3007
+ Tests []Test
3008
+ }
3009
+
3010
+ // RunTests runs every Test block, the way run_tests.py does: one line per test, then the totals.
3011
+ func RunTests(suites []Suite) {
3012
+ if !aborted {
3013
+ passed, failed := 0, 0
3014
+ for _, s := range suites {
3015
+ for _, t := range s.Tests {
3016
+ if err := Try(t.Run); err != nil {
3017
+ failed++
3018
+ Say(fmt.Sprintf("FAIL %s (%s, line %d)", t.Title, s.File, t.Line))
3019
+ Say(" " + describeError(err))
3020
+ } else {
3021
+ passed++
3022
+ Say(fmt.Sprintf("PASS %s (%s, line %d)", t.Title, s.File, t.Line))
3023
+ }
3024
+ }
3025
+ }
3026
+ total := passed + failed
3027
+ Say(fmt.Sprintf("%d test%s: %d passed, %d failed", total, plural(total), passed, failed))
3028
+ if failed > 0 {
3029
+ exitCode = 1
3030
+ }
3031
+ }
3032
+ out.Flush()
3033
+ os.Exit(exitCode)
3034
+ }
3035
+
3036
+ // Str / Shown: the text of a value inside {holes} and in say.
3037
+ func Str(v V) string { return PyStr(v) }
3038
+ func Shown(v V) string { return Show(v) }