@skillstech/thunderlang 1.2.0 → 1.4.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 +190 -0
- package/dist/core.cjs +6718 -1232
- package/dist/index.cjs +17490 -12204
- package/dist/learn.cjs +5866 -497
- package/package.json +6 -2
- package/src/cli-home.mjs +1 -1
- package/src/cli.mjs +54 -6
- package/src/core/ThunderRuntime.cs +1367 -0
- package/src/core/check.mjs +158 -2
- package/src/core/cli.mjs +148 -8
- package/src/core/csharp-run.mjs +184 -0
- package/src/core/diagnostics.mjs +13 -1
- package/src/core/engine-core.mjs +285 -2
- package/src/core/engine-values.mjs +1 -1
- package/src/core/format.mjs +191 -3
- package/src/core/go-run.mjs +106 -0
- package/src/core/index.mjs +2 -1
- package/src/core/java/thunder/T.java +6 -0
- package/src/core/java/thunder/ThunderRuntime.java +1374 -0
- package/src/core/java-run.mjs +89 -0
- package/src/core/parser.mjs +331 -5
- package/src/core/project.mjs +31 -6
- package/src/core/react-run.mjs +96 -0
- package/src/core/runtime-go/thunder_runtime.go +3038 -0
- package/src/core/runtime-react.mjs +133 -0
- package/src/core/rust/thunder_runtime.rs +1645 -0
- package/src/core/rust-run.mjs +192 -0
- package/src/core/screen-values.mjs +30 -0
- package/src/core/target-csharp.mjs +484 -0
- package/src/core/target-go.mjs +555 -0
- package/src/core/target-java.mjs +587 -0
- package/src/core/target-react.mjs +270 -0
- package/src/core/target-rust.mjs +534 -0
- package/src/core/target-typescript.mjs +2 -2
- package/src/core.d.ts +59 -0
- package/src/core.mjs +14 -0
- package/src/emit.mjs +1 -1
- package/src/faithful.mjs +34 -1
- package/src/flow/access.mjs +1451 -0
- package/src/flow/ts-parse.mjs +772 -0
- package/src/index.d.ts +3 -0
- package/src/index.mjs +3 -0
- package/src/libraries.mjs +32 -4
- package/src/model.mjs +72 -9
- package/src/passport-cli.mjs +101 -0
- package/src/passport-fs.d.mts +9 -0
- package/src/passport-fs.mjs +180 -0
- package/src/passport.d.mts +46 -0
- package/src/passport.mjs +255 -0
- package/src/program.d.mts +31 -0
- package/src/program.mjs +14 -0
- package/src/read-level.mjs +48 -2
- package/src/read-repo-fs.mjs +3 -1
- package/src/read.mjs +64 -5
- package/src/replay-cli.mjs +123 -0
- package/src/review.mjs +31 -3
- package/src/say-less.mjs +168 -13
- package/src/screens.mjs +833 -0
- package/src/steps.mjs +443 -20
- package/src/term.mjs +43 -0
- package/src/things-langs.mjs +20 -3
- package/src/write-across-cli.mjs +143 -0
- package/src/write-across.mjs +168 -0
|
@@ -0,0 +1,1367 @@
|
|
|
1
|
+
// ThunderRuntime.cs: written by the Thunder compiler next to compiled C#. Base class library only.
|
|
2
|
+
// The values and rules here are the Thunder engine's own (compiler/src/core/engine-values.mjs), ported line by line,
|
|
3
|
+
// so compiled C#, compiled TypeScript, the Thunder engine, and compiled Python say the same thing for the same program.
|
|
4
|
+
//
|
|
5
|
+
// Values: whole number -> BigInteger decimal number -> Dec (exact, like Python's Decimal)
|
|
6
|
+
// money -> Money text -> string yes/no -> bool nothing -> null
|
|
7
|
+
// list -> List<object> (a pair from a map is a Tuple) map -> PyDict
|
|
8
|
+
// record -> RecordVal date -> PyDate
|
|
9
|
+
#nullable disable
|
|
10
|
+
#pragma warning disable CS0162, CS0168, CS0219, CS8321
|
|
11
|
+
using System;
|
|
12
|
+
using System.Collections.Generic;
|
|
13
|
+
using System.IO;
|
|
14
|
+
using System.Linq;
|
|
15
|
+
using System.Numerics;
|
|
16
|
+
using System.Text;
|
|
17
|
+
using System.Threading;
|
|
18
|
+
|
|
19
|
+
namespace Thunder
|
|
20
|
+
{
|
|
21
|
+
public sealed class Where { public string file; public int line; public Where(string f, int l) { file = f; line = l; } }
|
|
22
|
+
|
|
23
|
+
/** Every error a Thunder program can raise: a Thunder error (TC5xx) or one Python itself would raise. */
|
|
24
|
+
public abstract class TErr : Exception
|
|
25
|
+
{
|
|
26
|
+
public List<Where> where;
|
|
27
|
+
public string pyType;
|
|
28
|
+
public bool thunder;
|
|
29
|
+
protected TErr(string message) : base(message) { }
|
|
30
|
+
}
|
|
31
|
+
public sealed class ThunderErr : TErr
|
|
32
|
+
{
|
|
33
|
+
public string code;
|
|
34
|
+
public ThunderErr(string code, string message, string pyType = "ThunderError") : base(message) { this.code = code; this.pyType = pyType; thunder = true; }
|
|
35
|
+
}
|
|
36
|
+
public sealed class PyErr : TErr
|
|
37
|
+
{
|
|
38
|
+
public object[] args;
|
|
39
|
+
public PyErr(string pyType, string message, object[] args = null) : base(message) { this.pyType = pyType; this.args = args ?? new object[] { message }; }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
public sealed class Frame { public string file; public int line; public Frame(string f, int l) { file = f; line = l; } }
|
|
43
|
+
|
|
44
|
+
// ── Exact decimals: Python's Decimal with its default context (28 digits, half-even when a result is too long) ──
|
|
45
|
+
public sealed class Dec
|
|
46
|
+
{
|
|
47
|
+
public readonly int s; public readonly BigInteger c; public readonly int e; // sign (0 or 1), coefficient >= 0, exponent
|
|
48
|
+
const int PREC = 28;
|
|
49
|
+
static readonly BigInteger TEN = 10;
|
|
50
|
+
public Dec(int s, BigInteger c, int e) { this.s = s; this.c = c; this.e = e; }
|
|
51
|
+
public static BigInteger Pow10(int n) => BigInteger.Pow(TEN, n);
|
|
52
|
+
static int Ndigits(BigInteger c) => c.IsZero ? 1 : c.ToString().Length;
|
|
53
|
+
public static Dec Of(object x) => x is Dec d ? d : x is BigInteger b ? Int(b) : x is bool t ? Int(t ? BigInteger.One : BigInteger.Zero) : null;
|
|
54
|
+
public static Dec Int(BigInteger n) => new Dec(n.Sign < 0 ? 1 : 0, BigInteger.Abs(n), 0);
|
|
55
|
+
static readonly System.Text.RegularExpressions.Regex NUM = new System.Text.RegularExpressions.Regex(@"^([+-]?)([0-9]*)(?:\.([0-9]*))?(?:[eE]([+-]?[0-9]+))?$");
|
|
56
|
+
public static Dec Parse(string text)
|
|
57
|
+
{
|
|
58
|
+
var m = NUM.Match(T.jsTrim(text).Replace("_", ""));
|
|
59
|
+
if (!m.Success || (m.Groups[2].Value == "" && !m.Groups[3].Success)) return null;
|
|
60
|
+
var frac = m.Groups[3].Success ? m.Groups[3].Value : "";
|
|
61
|
+
var digits = (m.Groups[2].Value + frac);
|
|
62
|
+
if (digits == "") digits = "0";
|
|
63
|
+
return new Dec(m.Groups[1].Value == "-" ? 1 : 0, BigInteger.Parse(digits), (m.Groups[4].Success ? int.Parse(m.Groups[4].Value) : 0) - frac.Length);
|
|
64
|
+
}
|
|
65
|
+
public bool IsZero() => c.IsZero;
|
|
66
|
+
public Dec Fix()
|
|
67
|
+
{
|
|
68
|
+
int d = Ndigits(c) - PREC;
|
|
69
|
+
if (d <= 0) return this;
|
|
70
|
+
var p = Pow10(d);
|
|
71
|
+
var q = BigInteger.Divide(c, p);
|
|
72
|
+
var r = BigInteger.Remainder(c, p);
|
|
73
|
+
var half = 5 * Pow10(d - 1);
|
|
74
|
+
if (r > half || (r == half && !q.IsEven)) q += 1;
|
|
75
|
+
int ee = e + d;
|
|
76
|
+
if (Ndigits(q) > PREC) { q /= TEN; ee += 1; }
|
|
77
|
+
return new Dec(s, q, ee);
|
|
78
|
+
}
|
|
79
|
+
public BigInteger Signed() => s == 1 ? -c : c;
|
|
80
|
+
public static Dec Add(Dec a, Dec b)
|
|
81
|
+
{
|
|
82
|
+
int ee = Math.Min(a.e, b.e);
|
|
83
|
+
var x = a.Signed() * Pow10(a.e - ee); var y = b.Signed() * Pow10(b.e - ee);
|
|
84
|
+
var sum = x + y;
|
|
85
|
+
int sg;
|
|
86
|
+
if (sum.IsZero) sg = a.s == 1 && b.s == 1 && a.c.IsZero && b.c.IsZero ? 1 : (a.c.IsZero && b.c.IsZero ? Math.Min(a.s, b.s) : 0);
|
|
87
|
+
else sg = sum.Sign < 0 ? 1 : 0;
|
|
88
|
+
return new Dec(sg, BigInteger.Abs(sum), ee).Fix();
|
|
89
|
+
}
|
|
90
|
+
public Dec Negated() => new Dec(s == 1 ? 0 : 1, c, e);
|
|
91
|
+
public static Dec Sub(Dec a, Dec b) => Add(a, b.Negated());
|
|
92
|
+
public static Dec Mul(Dec a, Dec b) => new Dec(a.s ^ b.s, a.c * b.c, a.e + b.e).Fix();
|
|
93
|
+
public static Dec Div(Dec a, Dec b)
|
|
94
|
+
{
|
|
95
|
+
int sg = a.s ^ b.s;
|
|
96
|
+
if (a.c.IsZero) return new Dec(sg, BigInteger.Zero, a.e - b.e).Fix();
|
|
97
|
+
int shift = Ndigits(b.c) - Ndigits(a.c) + PREC + 1;
|
|
98
|
+
int exp = a.e - b.e - shift;
|
|
99
|
+
BigInteger coeff, rem;
|
|
100
|
+
if (shift >= 0) { var n = a.c * Pow10(shift); coeff = BigInteger.DivRem(n, b.c, out rem); }
|
|
101
|
+
else { var d = b.c * Pow10(-shift); coeff = BigInteger.DivRem(a.c, d, out rem); }
|
|
102
|
+
if (!rem.IsZero) { if ((coeff % 5).IsZero) coeff += 1; }
|
|
103
|
+
else { int ideal = a.e - b.e; while (exp < ideal && (coeff % TEN).IsZero) { coeff /= TEN; exp += 1; } }
|
|
104
|
+
return new Dec(sg, coeff, exp).Fix();
|
|
105
|
+
}
|
|
106
|
+
public static Dec Rem(Dec a, Dec b)
|
|
107
|
+
{
|
|
108
|
+
int ee = Math.Min(a.e, b.e);
|
|
109
|
+
var x = a.c * Pow10(a.e - ee); var y = b.c * Pow10(b.e - ee);
|
|
110
|
+
return new Dec(a.s, x % y, ee).Fix();
|
|
111
|
+
}
|
|
112
|
+
public Dec Neg() => (c.IsZero ? new Dec(0, BigInteger.Zero, e) : Negated()).Fix();
|
|
113
|
+
public Dec Abs() => new Dec(0, c, e).Fix();
|
|
114
|
+
public static int Cmp(Dec a, Dec b)
|
|
115
|
+
{
|
|
116
|
+
int ee = Math.Min(a.e, b.e);
|
|
117
|
+
var x = a.Signed() * Pow10(a.e - ee); var y = b.Signed() * Pow10(b.e - ee);
|
|
118
|
+
return x < y ? -1 : x > y ? 1 : 0;
|
|
119
|
+
}
|
|
120
|
+
public Dec QuantizeHalfUp(int ee)
|
|
121
|
+
{
|
|
122
|
+
if (ee <= e) return new Dec(s, c * Pow10(e - ee), ee);
|
|
123
|
+
var p = Pow10(ee - e);
|
|
124
|
+
var q = BigInteger.Divide(c, p);
|
|
125
|
+
if ((c % p) * 2 >= p) q += 1;
|
|
126
|
+
return new Dec(s, q, ee);
|
|
127
|
+
}
|
|
128
|
+
public bool IsIntegral() { if (e >= 0) return true; return (c % Pow10(-e)).IsZero; }
|
|
129
|
+
public BigInteger ToBigInt() { var v = e >= 0 ? c * Pow10(e) : BigInteger.Divide(c, Pow10(-e)); return s == 1 ? -v : v; }
|
|
130
|
+
public override string ToString()
|
|
131
|
+
{
|
|
132
|
+
var digits = c.ToString();
|
|
133
|
+
int left = e + digits.Length;
|
|
134
|
+
int dot = e <= 0 && left > -6 ? left : 1;
|
|
135
|
+
string ip, fp;
|
|
136
|
+
if (dot <= 0) { ip = "0"; fp = "." + new string('0', -dot) + digits; }
|
|
137
|
+
else if (dot >= digits.Length) { ip = digits + new string('0', dot - digits.Length); fp = ""; }
|
|
138
|
+
else { ip = digits.Substring(0, dot); fp = "." + digits.Substring(dot); }
|
|
139
|
+
var ex = left == dot ? "" : "E" + (left - dot >= 0 ? "+" : "") + (left - dot);
|
|
140
|
+
return (s == 1 ? "-" : "") + ip + fp + ex;
|
|
141
|
+
}
|
|
142
|
+
public string ToFixed(int? places = null, bool group = false)
|
|
143
|
+
{
|
|
144
|
+
var d = this;
|
|
145
|
+
if (places != null) d = d.RoundHalfEven(-places.Value);
|
|
146
|
+
var digits = d.c.ToString();
|
|
147
|
+
int dot = d.e + digits.Length;
|
|
148
|
+
string ip, fp;
|
|
149
|
+
if (dot < 0) { ip = "0"; fp = new string('0', -dot) + digits; }
|
|
150
|
+
else if (dot > digits.Length) { ip = digits + new string('0', dot - digits.Length); fp = ""; }
|
|
151
|
+
else { ip = digits.Substring(0, dot); if (ip == "") ip = "0"; fp = digits.Substring(dot); }
|
|
152
|
+
if (group) ip = T.groupThousands(ip);
|
|
153
|
+
return (d.s == 1 ? "-" : "") + ip + (fp != "" ? "." + fp : "");
|
|
154
|
+
}
|
|
155
|
+
public Dec RoundHalfEven(int ee)
|
|
156
|
+
{
|
|
157
|
+
if (ee <= e) return new Dec(s, c * Pow10(e - ee), ee);
|
|
158
|
+
var p = Pow10(ee - e);
|
|
159
|
+
var q = BigInteger.Divide(c, p);
|
|
160
|
+
var r = BigInteger.Remainder(c, p);
|
|
161
|
+
if (r * 2 > p || (r * 2 == p && !q.IsEven)) q += 1;
|
|
162
|
+
return new Dec(s, q, ee);
|
|
163
|
+
}
|
|
164
|
+
public string Key()
|
|
165
|
+
{
|
|
166
|
+
if (c.IsZero) return "0";
|
|
167
|
+
var cc = c; int ee = e;
|
|
168
|
+
while ((cc % TEN).IsZero) { cc /= TEN; ee += 1; }
|
|
169
|
+
return (s == 1 ? "-" : "") + cc.ToString() + "e" + ee;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
public sealed class Money
|
|
174
|
+
{
|
|
175
|
+
public readonly Dec amount;
|
|
176
|
+
public Money(Dec amount) { this.amount = amount; }
|
|
177
|
+
public static Money Of(object x)
|
|
178
|
+
{
|
|
179
|
+
if (x is Money m) return m;
|
|
180
|
+
if (x is string str)
|
|
181
|
+
{
|
|
182
|
+
var d = Dec.Parse(str.Replace(",", "").Replace("$", "").Trim());
|
|
183
|
+
if (d == null) throw new PyErr("InvalidOperation", "[<class 'decimal.ConversionSyntax'>]");
|
|
184
|
+
return new Money(d);
|
|
185
|
+
}
|
|
186
|
+
return new Money(T.toDec(x));
|
|
187
|
+
}
|
|
188
|
+
public override string ToString()
|
|
189
|
+
{
|
|
190
|
+
var a = amount;
|
|
191
|
+
int places = a.e < 0 ? Math.Max(2, -a.e) : 2;
|
|
192
|
+
return (a.s == 1 && !a.c.IsZero ? "-$" : "$") + a.Abs().ToFixed(places, true);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
public sealed class PyDate
|
|
197
|
+
{
|
|
198
|
+
public readonly int y, m, d;
|
|
199
|
+
public PyDate(int y, int m, int d) { this.y = y; this.m = m; this.d = d; }
|
|
200
|
+
public string Iso() => y.ToString().PadLeft(4, '0') + "-" + m.ToString().PadLeft(2, '0') + "-" + d.ToString().PadLeft(2, '0');
|
|
201
|
+
public int Num() => y * 10000 + m * 100 + d;
|
|
202
|
+
public static PyDate Today() { var t = DateTime.Now; return new PyDate(t.Year, t.Month, t.Day); }
|
|
203
|
+
static readonly System.Text.RegularExpressions.Regex DATE = new System.Text.RegularExpressions.Regex(@"^([0-9]{4})-?([0-9]{2})-?([0-9]{2})$");
|
|
204
|
+
public static PyDate Parse(string text)
|
|
205
|
+
{
|
|
206
|
+
var mm = DATE.Match(text);
|
|
207
|
+
if (!mm.Success) return null;
|
|
208
|
+
int yy = int.Parse(mm.Groups[1].Value), mo = int.Parse(mm.Groups[2].Value), dd = int.Parse(mm.Groups[3].Value);
|
|
209
|
+
int[] days = { 31, (yy % 4 == 0 && yy % 100 != 0) || yy % 400 == 0 ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
|
|
210
|
+
if (yy < 1 || mo < 1 || mo > 12 || dd < 1 || dd > days[mo - 1]) return null;
|
|
211
|
+
return new PyDate(yy, mo, dd);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
public sealed class Tuple { public readonly List<object> items; public Tuple(List<object> items) { this.items = items; } }
|
|
216
|
+
|
|
217
|
+
public sealed class NotGiven { }
|
|
218
|
+
|
|
219
|
+
/** A Python dict: insertion order kept; keys equal the way Python compares them (1 == 1.0 == True). */
|
|
220
|
+
public sealed class PyDict
|
|
221
|
+
{
|
|
222
|
+
public readonly Dictionary<string, object[]> m = new Dictionary<string, object[]>();
|
|
223
|
+
public readonly List<string> order = new List<string>();
|
|
224
|
+
public static string KeyOf(object k)
|
|
225
|
+
{
|
|
226
|
+
if (k == null) return "N";
|
|
227
|
+
if (k is string str) return "s" + str;
|
|
228
|
+
if (k is bool || k is BigInteger || k is Dec) return "n" + Dec.Of(k).Key();
|
|
229
|
+
if (k is Money mo) return "m" + mo.amount.Key();
|
|
230
|
+
if (k is PyDate d) return "d" + d.Iso();
|
|
231
|
+
if (k is Tuple t) return "t(" + string.Join(",", t.items.Select(KeyOf)) + ")";
|
|
232
|
+
if (k is NotGiven) return "G";
|
|
233
|
+
throw T.TypeErr("unhashable type: '" + T.typeName(k) + "'");
|
|
234
|
+
}
|
|
235
|
+
public bool Has(object k) => m.ContainsKey(KeyOf(k));
|
|
236
|
+
public object Get(object k) => m.TryGetValue(KeyOf(k), out var e) ? e[1] : null;
|
|
237
|
+
public void Set(object k, object v)
|
|
238
|
+
{
|
|
239
|
+
var id = KeyOf(k);
|
|
240
|
+
if (m.TryGetValue(id, out var e)) e[1] = v; else { m[id] = new object[] { k, v }; order.Add(id); }
|
|
241
|
+
}
|
|
242
|
+
public void Delete(object k) { var id = KeyOf(k); if (m.Remove(id)) order.Remove(id); }
|
|
243
|
+
public int Size => m.Count;
|
|
244
|
+
public IEnumerable<object[]> Entries() { foreach (var id in order) yield return m[id]; }
|
|
245
|
+
public List<object> Keys() => Entries().Select(e => e[0]).ToList();
|
|
246
|
+
public List<object> Values() => Entries().Select(e => e[1]).ToList();
|
|
247
|
+
public List<object> Items() => Entries().Select(e => (object)new Tuple(new List<object> { e[0], e[1] })).ToList();
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
public sealed class FieldDef { public string py; public string k; public FieldDef(string py, string k) { this.py = py; this.k = k; } }
|
|
251
|
+
public sealed class Rule { public Func<object, object> cond; public string text; public int line; public Rule(Func<object, object> c, string t, int l) { cond = c; text = t; line = l; } }
|
|
252
|
+
public sealed class RecordKind
|
|
253
|
+
{
|
|
254
|
+
public string py; public List<FieldDef> fields; public Dictionary<string, Rule[]> rules;
|
|
255
|
+
}
|
|
256
|
+
public sealed class RecordVal
|
|
257
|
+
{
|
|
258
|
+
public readonly RecordKind cls;
|
|
259
|
+
public readonly Dictionary<string, object> f = new Dictionary<string, object>();
|
|
260
|
+
public RecordVal(RecordKind cls) { this.cls = cls; }
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Sorting the way V8's Array.prototype.sort does (TimSort), so a comparison that fails fails on the same pair. */
|
|
264
|
+
static class V8Sort
|
|
265
|
+
{
|
|
266
|
+
public static void Sort<TItem>(TItem[] a, Func<TItem, TItem, int> cmp)
|
|
267
|
+
{
|
|
268
|
+
int length = a.Length;
|
|
269
|
+
if (length < 2) return;
|
|
270
|
+
int remaining = length, low = 0;
|
|
271
|
+
int minRun = MinRun(remaining);
|
|
272
|
+
var runs = new List<(int, int)>();
|
|
273
|
+
while (remaining != 0)
|
|
274
|
+
{
|
|
275
|
+
int run = CountAndMakeRun(a, low, low + remaining, cmp);
|
|
276
|
+
if (run < minRun)
|
|
277
|
+
{
|
|
278
|
+
int forced = Math.Min(minRun, remaining);
|
|
279
|
+
BinaryInsertion(a, low, low + run, low + forced, cmp);
|
|
280
|
+
run = forced;
|
|
281
|
+
}
|
|
282
|
+
runs.Add((low, run));
|
|
283
|
+
low += run; remaining -= run;
|
|
284
|
+
}
|
|
285
|
+
// Longer arrays (64 or more items): merge the runs in order (stable).
|
|
286
|
+
while (runs.Count > 1)
|
|
287
|
+
{
|
|
288
|
+
var (b1, l1) = runs[0]; var (b2, l2) = runs[1];
|
|
289
|
+
var merged = new TItem[l1 + l2];
|
|
290
|
+
int i = b1, j = b2, k = 0;
|
|
291
|
+
while (i < b1 + l1 && j < b2 + l2) merged[k++] = cmp(a[j], a[i]) < 0 ? a[j++] : a[i++];
|
|
292
|
+
while (i < b1 + l1) merged[k++] = a[i++];
|
|
293
|
+
while (j < b2 + l2) merged[k++] = a[j++];
|
|
294
|
+
Array.Copy(merged, 0, a, b1, merged.Length);
|
|
295
|
+
runs.RemoveAt(1); runs[0] = (b1, l1 + l2);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
static int MinRun(int n) { int r = 0; while (n >= 64) { r |= n & 1; n >>= 1; } return n + r; }
|
|
299
|
+
static int CountAndMakeRun<TItem>(TItem[] a, int lowArg, int high, Func<TItem, TItem, int> cmp)
|
|
300
|
+
{
|
|
301
|
+
int low = lowArg + 1;
|
|
302
|
+
if (low == high) return 1;
|
|
303
|
+
int runLength = 2;
|
|
304
|
+
var elementLow = a[low]; var elementLowPre = a[low - 1];
|
|
305
|
+
int order = cmp(elementLow, elementLowPre);
|
|
306
|
+
bool desc = order < 0;
|
|
307
|
+
var previous = elementLow;
|
|
308
|
+
for (int idx = low + 1; idx < high; ++idx)
|
|
309
|
+
{
|
|
310
|
+
var current = a[idx];
|
|
311
|
+
order = cmp(current, previous);
|
|
312
|
+
if (desc) { if (order >= 0) break; }
|
|
313
|
+
else { if (order < 0) break; }
|
|
314
|
+
previous = current;
|
|
315
|
+
++runLength;
|
|
316
|
+
}
|
|
317
|
+
if (desc) Array.Reverse(a, lowArg, runLength);
|
|
318
|
+
return runLength;
|
|
319
|
+
}
|
|
320
|
+
static void BinaryInsertion<TItem>(TItem[] a, int low, int startArg, int high, Func<TItem, TItem, int> cmp)
|
|
321
|
+
{
|
|
322
|
+
int start = low == startArg ? startArg + 1 : startArg;
|
|
323
|
+
for (; start < high; ++start)
|
|
324
|
+
{
|
|
325
|
+
int left = low, right = start;
|
|
326
|
+
var pivot = a[start];
|
|
327
|
+
while (left < right)
|
|
328
|
+
{
|
|
329
|
+
int mid = left + ((right - left) >> 1);
|
|
330
|
+
int order = cmp(pivot, a[mid]);
|
|
331
|
+
if (order < 0) right = mid; else left = mid + 1;
|
|
332
|
+
}
|
|
333
|
+
for (int p = start; p > left; --p) a[p] = a[p - 1];
|
|
334
|
+
a[left] = pivot;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
public static partial class T
|
|
340
|
+
{
|
|
341
|
+
public static readonly object NOT_GIVEN = new NotGiven();
|
|
342
|
+
public const int MAX_FRAMES = 997;
|
|
343
|
+
|
|
344
|
+
// ── Errors ──────────────────────────────────────────────────────────────────────────────────────────────
|
|
345
|
+
public static ThunderErr Stop(object m) => new ThunderErr("TC507", (string)m, "Stop");
|
|
346
|
+
public static ThunderErr RuleBroken(string m) => new ThunderErr("TC504", m, "RuleBroken");
|
|
347
|
+
public static ThunderErr ExpectationFailed(string m) => new ThunderErr("TC505", m, "ExpectationFailed");
|
|
348
|
+
public static ThunderErr KindMismatch(string m) => new ThunderErr("TC506", m, "TypeError");
|
|
349
|
+
public static ThunderErr ConversionFailed(string m) => new ThunderErr("TC509", m, "ValueError");
|
|
350
|
+
public static ThunderErr MissingValue(string m) => new ThunderErr("TC503", m, "LookupError");
|
|
351
|
+
public static ThunderErr DividedByZero(string m) => new ThunderErr("TC501", m, "ZeroDivisionError");
|
|
352
|
+
public static PyErr TypeErr(string m) => new PyErr("TypeError", m);
|
|
353
|
+
|
|
354
|
+
public static string explain(TErr e)
|
|
355
|
+
{
|
|
356
|
+
if (e.thunder) return e.Message;
|
|
357
|
+
var t = e.pyType;
|
|
358
|
+
if (t == "ZeroDivisionError" || t == "DivisionByZero") return "You divided by zero.";
|
|
359
|
+
if (t == "InvalidOperation") return "This calculation has no answer (for example, zero divided by zero).";
|
|
360
|
+
if (t == "KeyError") return "There is no entry for " + show(((PyErr)e).args.Length > 0 ? ((PyErr)e).args[0] : null) + ".";
|
|
361
|
+
if ((t == "TypeError" || t == "AttributeError") && e.Message.Contains("NoneType")) return "A value was nothing where a value was needed.";
|
|
362
|
+
if (t == "TypeError") return "Values of different kinds were mixed (" + e.Message + ").";
|
|
363
|
+
if (t == "RecursionError") return "A function called itself too many times.";
|
|
364
|
+
return t + ": " + e.Message;
|
|
365
|
+
}
|
|
366
|
+
public static string codeOf(TErr e)
|
|
367
|
+
{
|
|
368
|
+
if (e is ThunderErr te) return te.code;
|
|
369
|
+
var t = e.pyType;
|
|
370
|
+
if (t == "ZeroDivisionError" || t == "DivisionByZero") return "TC501";
|
|
371
|
+
if ((t == "TypeError" || t == "AttributeError") && e.Message.Contains("NoneType")) return "TC502";
|
|
372
|
+
if (t == "KeyError") return "TC503";
|
|
373
|
+
if (t == "TypeError") return "TC506";
|
|
374
|
+
return "TC508";
|
|
375
|
+
}
|
|
376
|
+
public static TErr asPyErr(Exception e)
|
|
377
|
+
{
|
|
378
|
+
if (e is TErr t) return t;
|
|
379
|
+
if (e is InsufficientExecutionStackException) return new PyErr("RecursionError", "maximum recursion depth exceeded");
|
|
380
|
+
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e).Throw();
|
|
381
|
+
return null;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// ── JavaScript string behavior the engine relies on ───────────────────────────────────────────────────────
|
|
385
|
+
/** Code points, the way JavaScript's Array.from(string) splits text (a lone surrogate stays itself). */
|
|
386
|
+
public static List<string> chars(string s)
|
|
387
|
+
{
|
|
388
|
+
var out_ = new List<string>(s.Length);
|
|
389
|
+
for (int i = 0; i < s.Length;)
|
|
390
|
+
{
|
|
391
|
+
if (char.IsHighSurrogate(s[i]) && i + 1 < s.Length && char.IsLowSurrogate(s[i + 1])) { out_.Add(s.Substring(i, 2)); i += 2; }
|
|
392
|
+
else { out_.Add(s[i].ToString()); i++; }
|
|
393
|
+
}
|
|
394
|
+
return out_;
|
|
395
|
+
}
|
|
396
|
+
static int cp(string ch) => ch.Length == 2 ? char.ConvertToUtf32(ch[0], ch[1]) : ch[0];
|
|
397
|
+
/** JavaScript's \s (with the u flag). */
|
|
398
|
+
static bool jsSpace(char ch) => ch == '\t' || ch == '\n' || ch == '\v' || ch == '\f' || ch == '\r' || ch == ' ' || ch == '\u00a0' || ch == '\u1680' || (ch >= '\u2000' && ch <= '\u200a') || ch == '\u2028' || ch == '\u2029' || ch == '\u202f' || ch == '\u205f' || ch == '\u3000' || ch == '\ufeff';
|
|
399
|
+
static bool pySpace(char ch) => jsSpace(ch) || (ch >= '\x1c' && ch <= '\x1f') || ch == '\x85';
|
|
400
|
+
public static string jsTrim(string s) { int i = 0, j = s.Length; while (i < j && jsSpace(s[i])) i++; while (j > i && jsSpace(s[j - 1])) j--; return s.Substring(i, j - i); }
|
|
401
|
+
public static string pyStrip(string s) { int i = 0, j = s.Length; while (i < j && pySpace(s[i])) i++; while (j > i && pySpace(s[j - 1])) j--; return s.Substring(i, j - i); }
|
|
402
|
+
public static List<object> pySplit(string s)
|
|
403
|
+
{
|
|
404
|
+
var out_ = new List<object>(); var sb = new StringBuilder();
|
|
405
|
+
foreach (var ch in s) { if (pySpace(ch)) { if (sb.Length > 0) { out_.Add(sb.ToString()); sb.Clear(); } } else sb.Append(ch); }
|
|
406
|
+
if (sb.Length > 0) out_.Add(sb.ToString());
|
|
407
|
+
return out_;
|
|
408
|
+
}
|
|
409
|
+
public static List<object> splitLines(string s)
|
|
410
|
+
{
|
|
411
|
+
var out_ = new List<object>(); int start = 0, i = 0;
|
|
412
|
+
while (i < s.Length)
|
|
413
|
+
{
|
|
414
|
+
char ch = s[i];
|
|
415
|
+
if (ch == '\r' && i + 1 < s.Length && s[i + 1] == '\n') { out_.Add(s.Substring(start, i - start)); i += 2; start = i; continue; }
|
|
416
|
+
if (ch == '\n' || ch == '\r' || ch == '\v' || ch == '\f' || ch == '\x1c' || ch == '\x1d' || ch == '\x1e' || ch == '\x85' || ch == '\u2028' || ch == '\u2029') { out_.Add(s.Substring(start, i - start)); i++; start = i; continue; }
|
|
417
|
+
i++;
|
|
418
|
+
}
|
|
419
|
+
if (start < s.Length) out_.Add(s.Substring(start));
|
|
420
|
+
return out_;
|
|
421
|
+
}
|
|
422
|
+
public static string groupThousands(string ip)
|
|
423
|
+
{
|
|
424
|
+
var sb = new StringBuilder();
|
|
425
|
+
for (int i = 0; i < ip.Length; i++) { if (i > 0 && (ip.Length - i) % 3 == 0) sb.Append(','); sb.Append(ip[i]); }
|
|
426
|
+
return sb.ToString();
|
|
427
|
+
}
|
|
428
|
+
static string jsLower(string s) => s.ToLowerInvariant();
|
|
429
|
+
static string jsUpper(string s) => s.ToUpperInvariant().Replace("ß", "SS");
|
|
430
|
+
|
|
431
|
+
// ── Kinds ───────────────────────────────────────────────────────────────────────────────────────────────
|
|
432
|
+
public static bool isInt(object x) => x is BigInteger;
|
|
433
|
+
public static bool isNumber(object x) => x is BigInteger || x is Dec;
|
|
434
|
+
static bool isIntLike(object x) => x is BigInteger || x is bool;
|
|
435
|
+
static bool isNumLike(object x) => isIntLike(x) || x is Dec;
|
|
436
|
+
static BigInteger asBig(object x) => x is bool b ? (b ? BigInteger.One : BigInteger.Zero) : (BigInteger)x;
|
|
437
|
+
static int numCmp(object a, object b)
|
|
438
|
+
{
|
|
439
|
+
if (isIntLike(a) && isIntLike(b)) { var x = asBig(a); var y = asBig(b); return x < y ? -1 : x > y ? 1 : 0; }
|
|
440
|
+
return Dec.Cmp(Dec.Of(a), Dec.Of(b));
|
|
441
|
+
}
|
|
442
|
+
/** JavaScript's a === b: equal primitives, or the same object. */
|
|
443
|
+
static bool same(object a, object b)
|
|
444
|
+
{
|
|
445
|
+
if (a == null || b == null) return a == null && b == null;
|
|
446
|
+
if (a is BigInteger x && b is BigInteger y) return x == y;
|
|
447
|
+
if (a is string s1 && b is string s2) return string.Equals(s1, s2, StringComparison.Ordinal);
|
|
448
|
+
if (a is bool b1 && b is bool b2) return b1 == b2;
|
|
449
|
+
return ReferenceEquals(a, b);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
public static string typeName(object v)
|
|
453
|
+
{
|
|
454
|
+
if (v == null) return "NoneType";
|
|
455
|
+
if (v is bool) return "bool";
|
|
456
|
+
if (v is BigInteger) return "int";
|
|
457
|
+
if (v is string) return "str";
|
|
458
|
+
if (v is Dec) return "decimal.Decimal";
|
|
459
|
+
if (v is Money) return "Money";
|
|
460
|
+
if (v is List<object>) return "list";
|
|
461
|
+
if (v is Tuple) return "tuple";
|
|
462
|
+
if (v is PyDict) return "dict";
|
|
463
|
+
if (v is PyDate) return "datetime.date";
|
|
464
|
+
if (v is RecordVal r) return r.cls.py;
|
|
465
|
+
if (v is NotGiven) return "_NotGiven";
|
|
466
|
+
return "object";
|
|
467
|
+
}
|
|
468
|
+
static string shortName(object v) => v is Dec ? "Decimal" : v is PyDate ? "date" : typeName(v);
|
|
469
|
+
|
|
470
|
+
public static string describe(object v)
|
|
471
|
+
{
|
|
472
|
+
if (v == null) return "nothing";
|
|
473
|
+
if (v is bool) return "a yes/no value";
|
|
474
|
+
if (v is string s) return "the text \"" + s + "\"";
|
|
475
|
+
if (isNumber(v)) return "the number " + show(v);
|
|
476
|
+
if (v is Money m) return m.ToString();
|
|
477
|
+
return "a value (" + shortName(v) + ")";
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
public static string show(object v)
|
|
481
|
+
{
|
|
482
|
+
if (v == null) return "nothing";
|
|
483
|
+
if (v is bool b) return b ? "yes" : "no";
|
|
484
|
+
if (v is Dec d) { var t = d.ToFixed(); return t.Contains('.') ? t.TrimEnd('0').TrimEnd('.') : t; }
|
|
485
|
+
if (v is List<object> l) return "[" + string.Join(", ", l.Select(show)) + "]";
|
|
486
|
+
if (v is Tuple tu) return "[" + string.Join(", ", tu.items.Select(show)) + "]";
|
|
487
|
+
if (v is PyDict m) return "{" + string.Join(", ", m.Entries().Select(e => show(e[0]) + ": " + show(e[1]))) + "}";
|
|
488
|
+
if (v is RecordVal r) return r.cls.py + "(" + string.Join(", ", r.cls.fields.Select(f => f.py.Replace("_", " ") + ": " + show(r.f.TryGetValue(f.py, out var x) ? x : null))) + ")";
|
|
489
|
+
if (v is PyDate dt) return dt.Iso();
|
|
490
|
+
return pyStr(v);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
public static string pyRepr(object v)
|
|
494
|
+
{
|
|
495
|
+
if (v is string str)
|
|
496
|
+
{
|
|
497
|
+
char q = str.Contains('\'') && !str.Contains('"') ? '"' : '\'';
|
|
498
|
+
var sb = new StringBuilder();
|
|
499
|
+
foreach (var ch in chars(str))
|
|
500
|
+
{
|
|
501
|
+
int c = cp(ch);
|
|
502
|
+
if (ch == "\\") sb.Append("\\\\");
|
|
503
|
+
else if (ch == q.ToString()) sb.Append('\\').Append(q);
|
|
504
|
+
else if (ch == "\n") sb.Append("\\n");
|
|
505
|
+
else if (ch == "\r") sb.Append("\\r");
|
|
506
|
+
else if (ch == "\t") sb.Append("\\t");
|
|
507
|
+
else if (c < 0x20 || c == 0x7f) sb.Append("\\x").Append(c.ToString("x2"));
|
|
508
|
+
else sb.Append(ch);
|
|
509
|
+
}
|
|
510
|
+
return q + sb.ToString() + q;
|
|
511
|
+
}
|
|
512
|
+
if (v == null) return "None";
|
|
513
|
+
if (v is bool b) return b ? "True" : "False";
|
|
514
|
+
if (v is BigInteger i) return i.ToString();
|
|
515
|
+
if (v is Dec d) return "Decimal('" + d.ToString() + "')";
|
|
516
|
+
if (v is Money mo) return "Money('" + mo.amount.ToFixed() + "')";
|
|
517
|
+
if (v is List<object> l) return "[" + string.Join(", ", l.Select(pyRepr)) + "]";
|
|
518
|
+
if (v is Tuple t) return t.items.Count == 1 ? "(" + pyRepr(t.items[0]) + ",)" : "(" + string.Join(", ", t.items.Select(pyRepr)) + ")";
|
|
519
|
+
if (v is PyDict m) return "{" + string.Join(", ", m.Entries().Select(e => pyRepr(e[0]) + ": " + pyRepr(e[1]))) + "}";
|
|
520
|
+
if (v is PyDate dt) return "datetime.date(" + dt.y + ", " + dt.m + ", " + dt.d + ")";
|
|
521
|
+
if (v is RecordVal r) return r.cls.py + "(" + string.Join(", ", r.cls.fields.Select(f => f.py + "=" + pyRepr(r.f.TryGetValue(f.py, out var x) ? x : null))) + ")";
|
|
522
|
+
if (v is NotGiven) return "not given";
|
|
523
|
+
return v.ToString();
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
public static string pyStr(object v)
|
|
527
|
+
{
|
|
528
|
+
if (v is string s) return s;
|
|
529
|
+
if (v is Money m) return m.ToString();
|
|
530
|
+
if (v is PyDate d) return d.Iso();
|
|
531
|
+
if (v is Dec dc) return dc.ToString();
|
|
532
|
+
return pyRepr(v);
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
public static bool truthy(object v)
|
|
536
|
+
{
|
|
537
|
+
if (v == null) return false;
|
|
538
|
+
if (v is bool b) return b;
|
|
539
|
+
if (v is BigInteger i) return !i.IsZero;
|
|
540
|
+
if (v is Dec d) return !d.IsZero();
|
|
541
|
+
if (v is string s) return s.Length > 0;
|
|
542
|
+
if (v is List<object> l) return l.Count > 0;
|
|
543
|
+
if (v is Tuple t) return t.items.Count > 0;
|
|
544
|
+
if (v is PyDict m) return m.Size > 0;
|
|
545
|
+
return true;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
public static bool yesNo(object v)
|
|
549
|
+
{
|
|
550
|
+
if (v is bool b) return b;
|
|
551
|
+
throw KindMismatch("This needs a yes/no value, but it is " + describe(v) + ". Compare it instead, for example: is 0, is empty, is nothing.");
|
|
552
|
+
}
|
|
553
|
+
/** A value the compiler knows is yes/no. */
|
|
554
|
+
public static bool B(object v) => (bool)v;
|
|
555
|
+
|
|
556
|
+
public static Dec toDec(object x)
|
|
557
|
+
{
|
|
558
|
+
if (x is Dec d) return d;
|
|
559
|
+
if (x is bool) throw KindMismatch("A yes/no value was used where a number was needed.");
|
|
560
|
+
if (x is BigInteger i) return Dec.Int(i);
|
|
561
|
+
if (x == null) throw KindMismatch("A value was nothing where a number was needed.");
|
|
562
|
+
throw KindMismatch(describe(x) + " was used where a number was needed.");
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
static Dec moneyOther(object other, string verb)
|
|
566
|
+
{
|
|
567
|
+
if (other is Money m) return m.amount;
|
|
568
|
+
if (isNumber(other) && numCmp(other, BigInteger.Zero) == 0) return Dec.Int(BigInteger.Zero);
|
|
569
|
+
throw KindMismatch("I can't " + verb + " money and " + describe(other) + ". Write the number as money, for example $5.");
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// ── Python operators ──────────────────────────────────────────────────────────────────────────────────────
|
|
573
|
+
public static object pyLen(object v)
|
|
574
|
+
{
|
|
575
|
+
if (v is string s) return new BigInteger(chars(s).Count);
|
|
576
|
+
if (v is List<object> l) return new BigInteger(l.Count);
|
|
577
|
+
if (v is Tuple t) return new BigInteger(t.items.Count);
|
|
578
|
+
if (v is PyDict m) return new BigInteger(m.Size);
|
|
579
|
+
throw TypeErr("object of type '" + typeName(v) + "' has no len()");
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** Iterate the way the engine does: a list as it grows (Python's list iterator), text by code point, a map's keys. */
|
|
583
|
+
public static IEnumerable<object> pyIter(object v)
|
|
584
|
+
{
|
|
585
|
+
if (v is List<object> l) return ListIter(l);
|
|
586
|
+
if (v is Tuple t) return ListIter(t.items);
|
|
587
|
+
if (v is string s) return chars(s).Cast<object>().ToList();
|
|
588
|
+
if (v is PyDict m) return m.Keys();
|
|
589
|
+
throw TypeErr("'" + typeName(v) + "' object is not iterable");
|
|
590
|
+
}
|
|
591
|
+
static IEnumerable<object> ListIter(List<object> l) { for (int i = 0; i < l.Count; i++) yield return l[i]; }
|
|
592
|
+
public static List<object> pyList(object v) => pyIter(v).ToList();
|
|
593
|
+
|
|
594
|
+
public static object add(object a, object b)
|
|
595
|
+
{
|
|
596
|
+
if (a is Money ma) return new Money(Dec.Add(ma.amount, moneyOther(b, "add")));
|
|
597
|
+
if (b is Money mb) return new Money(Dec.Add(mb.amount, moneyOther(a, "add")));
|
|
598
|
+
if (isIntLike(a) && isIntLike(b)) return asBig(a) + asBig(b);
|
|
599
|
+
if (isNumLike(a) && isNumLike(b)) return Dec.Add(Dec.Of(a), Dec.Of(b));
|
|
600
|
+
if (a is string sa) { if (b is string sb) return sa + sb; throw TypeErr("can only concatenate str (not \"" + typeName(b) + "\") to str"); }
|
|
601
|
+
if (a is List<object> la) { if (b is List<object> lb) { var r = new List<object>(la); r.AddRange(lb); return r; } throw TypeErr("can only concatenate list (not \"" + typeName(b) + "\") to list"); }
|
|
602
|
+
if (a is Tuple ta) { if (b is Tuple tb) { var r = new List<object>(ta.items); r.AddRange(tb.items); return new Tuple(r); } throw TypeErr("can only concatenate tuple (not \"" + typeName(b) + "\") to tuple"); }
|
|
603
|
+
throw TypeErr("unsupported operand type(s) for +: '" + typeName(a) + "' and '" + typeName(b) + "'");
|
|
604
|
+
}
|
|
605
|
+
public static object sub(object a, object b)
|
|
606
|
+
{
|
|
607
|
+
if (a is Money ma) return new Money(Dec.Sub(ma.amount, moneyOther(b, "subtract")));
|
|
608
|
+
if (b is Money mb) return new Money(Dec.Sub(moneyOther(a, "subtract"), mb.amount));
|
|
609
|
+
if (isIntLike(a) && isIntLike(b)) return asBig(a) - asBig(b);
|
|
610
|
+
if (isNumLike(a) && isNumLike(b)) return Dec.Sub(Dec.Of(a), Dec.Of(b));
|
|
611
|
+
throw TypeErr("unsupported operand type(s) for -: '" + typeName(a) + "' and '" + typeName(b) + "'");
|
|
612
|
+
}
|
|
613
|
+
static object repeat(object seq, object n)
|
|
614
|
+
{
|
|
615
|
+
var big = asBig(n);
|
|
616
|
+
int k = big > int.MaxValue ? int.MaxValue : big < 0 ? 0 : (int)big;
|
|
617
|
+
if (seq is string s) { if (k <= 0) return ""; var sb = new StringBuilder(); for (int i = 0; i < k; i++) sb.Append(s); return sb.ToString(); }
|
|
618
|
+
var l = (List<object>)seq; var out_ = new List<object>(); for (int i = 0; i < k; i++) out_.AddRange(l); return out_;
|
|
619
|
+
}
|
|
620
|
+
public static object mul(object a, object b)
|
|
621
|
+
{
|
|
622
|
+
if (a is Money ma) { if (b is Money) throw KindMismatch("Money can't be multiplied by money."); return new Money(Dec.Mul(ma.amount, toDec(b))); }
|
|
623
|
+
if (b is Money mb) return new Money(Dec.Mul(mb.amount, toDec(a)));
|
|
624
|
+
if (isIntLike(a) && isIntLike(b)) return asBig(a) * asBig(b);
|
|
625
|
+
if (isNumLike(a) && isNumLike(b)) return Dec.Mul(Dec.Of(a), Dec.Of(b));
|
|
626
|
+
bool seq(object x) => x is string || x is List<object>;
|
|
627
|
+
if (seq(a)) { if (isIntLike(b)) return repeat(a, b); throw TypeErr("can't multiply sequence by non-int of type '" + typeName(b) + "'"); }
|
|
628
|
+
if (seq(b)) { if (isIntLike(a)) return repeat(b, a); throw TypeErr("can't multiply sequence by non-int of type '" + typeName(a) + "'"); }
|
|
629
|
+
throw TypeErr("unsupported operand type(s) for *: '" + typeName(a) + "' and '" + typeName(b) + "'");
|
|
630
|
+
}
|
|
631
|
+
public static object neg(object a)
|
|
632
|
+
{
|
|
633
|
+
if (a is Money m) return new Money(m.amount.Neg());
|
|
634
|
+
if (isIntLike(a)) return -asBig(a);
|
|
635
|
+
if (a is Dec d) return d.Neg();
|
|
636
|
+
throw TypeErr("bad operand type for unary -: '" + typeName(a) + "'");
|
|
637
|
+
}
|
|
638
|
+
public static object intMod(object a, object b)
|
|
639
|
+
{
|
|
640
|
+
if (!isIntLike(a) || !isIntLike(b))
|
|
641
|
+
{
|
|
642
|
+
if (isNumLike(a) && isNumLike(b)) return modulo(a, b);
|
|
643
|
+
throw TypeErr("unsupported operand type(s) for %: '" + typeName(a) + "' and '" + typeName(b) + "'");
|
|
644
|
+
}
|
|
645
|
+
var x = asBig(a); var y = asBig(b);
|
|
646
|
+
if (y.IsZero) throw new PyErr("ZeroDivisionError", "integer modulo by zero");
|
|
647
|
+
var r = BigInteger.Remainder(x, y);
|
|
648
|
+
if (!r.IsZero && (r.Sign < 0) != (y.Sign < 0)) r += y;
|
|
649
|
+
return r;
|
|
650
|
+
}
|
|
651
|
+
public static object divide(object a, object b)
|
|
652
|
+
{
|
|
653
|
+
if (a is Money ma)
|
|
654
|
+
{
|
|
655
|
+
if (b is Money mb) { if (mb.amount.IsZero()) throw DividedByZero("You divided by zero."); return Dec.Div(ma.amount, mb.amount); }
|
|
656
|
+
var d = toDec(b);
|
|
657
|
+
if (d.IsZero()) throw DividedByZero("You divided by zero.");
|
|
658
|
+
return new Money(Dec.Div(ma.amount, d));
|
|
659
|
+
}
|
|
660
|
+
if (b is Money) throw KindMismatch("A plain number can't be divided by money.");
|
|
661
|
+
var x = toDec(a); var y = toDec(b);
|
|
662
|
+
if (y.IsZero()) throw DividedByZero("You divided by zero.");
|
|
663
|
+
return Dec.Div(x, y);
|
|
664
|
+
}
|
|
665
|
+
public static object modulo(object a, object b)
|
|
666
|
+
{
|
|
667
|
+
bool money = a is Money;
|
|
668
|
+
var x = money ? ((Money)a).amount : toDec(a);
|
|
669
|
+
var y = b is Money mb ? mb.amount : toDec(b);
|
|
670
|
+
if (y.IsZero()) throw DividedByZero("You divided by zero.");
|
|
671
|
+
var r = Dec.Rem(x, y);
|
|
672
|
+
if (!r.IsZero() && (r.s == 1) != (y.s == 1 && !y.IsZero())) r = Dec.Add(r, y);
|
|
673
|
+
if (money) return new Money(r);
|
|
674
|
+
return a is BigInteger && b is BigInteger ? (object)r.ToBigInt() : r;
|
|
675
|
+
}
|
|
676
|
+
public static object roundTo(object x, object places = null)
|
|
677
|
+
{
|
|
678
|
+
if (places == null) places = BigInteger.Zero;
|
|
679
|
+
var pb = places is Dec pd ? pd.ToBigInt() : asBig(places);
|
|
680
|
+
int p = (int)pb;
|
|
681
|
+
if (x is Money m) return new Money(m.amount.QuantizeHalfUp(-p));
|
|
682
|
+
if (x is BigInteger) return x;
|
|
683
|
+
var d = toDec(x).QuantizeHalfUp(-p);
|
|
684
|
+
return p == 0 ? (object)d.ToBigInt() : d;
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
public static bool eq(object a, object b)
|
|
688
|
+
{
|
|
689
|
+
if (same(a, b) && !(a is Dec)) return true;
|
|
690
|
+
if (a is Money || b is Money)
|
|
691
|
+
{
|
|
692
|
+
var m = a is Money ? (Money)a : (Money)b; var o = a is Money ? b : a;
|
|
693
|
+
if (o == null || o is string || o is bool) return false;
|
|
694
|
+
return Dec.Cmp(m.amount, moneyOther(o, "compare")) == 0;
|
|
695
|
+
}
|
|
696
|
+
if (a == null || b == null) return false;
|
|
697
|
+
if (isNumLike(a) && isNumLike(b)) return numCmp(a, b) == 0;
|
|
698
|
+
if (a is string || b is string) return same(a, b);
|
|
699
|
+
if (a is List<object> la && b is List<object> lb) { if (la.Count != lb.Count) return false; for (int i = 0; i < la.Count; i++) if (!(same(la[i], lb[i]) || eq(la[i], lb[i]))) return false; return true; }
|
|
700
|
+
if (a is Tuple ta && b is Tuple tb) { if (ta.items.Count != tb.items.Count) return false; for (int i = 0; i < ta.items.Count; i++) if (!eq(ta.items[i], tb.items[i])) return false; return true; }
|
|
701
|
+
if (a is PyDict da && b is PyDict db) return da.Size == db.Size && da.Entries().All(e => db.m.ContainsKey(PyDict.KeyOf(e[0])) && eq(e[1], db.m[PyDict.KeyOf(e[0])][1]));
|
|
702
|
+
if (a is RecordVal ra && b is RecordVal rb) return ReferenceEquals(ra.cls, rb.cls) && ra.cls.fields.All(f => eq(ra.f.TryGetValue(f.py, out var x) ? x : null, rb.f.TryGetValue(f.py, out var y) ? y : null));
|
|
703
|
+
if (a is PyDate pa && b is PyDate pb) return pa.Num() == pb.Num();
|
|
704
|
+
return false;
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
static string flip(string op) => op == "<" ? ">" : op == ">" ? "<" : op == "<=" ? ">=" : op == ">=" ? "<=" : op;
|
|
708
|
+
static bool holds(string op, int c) => op == "<" ? c < 0 : op == ">" ? c > 0 : op == "<=" ? c <= 0 : c >= 0;
|
|
709
|
+
|
|
710
|
+
public static bool compare(string op, object a, object b)
|
|
711
|
+
{
|
|
712
|
+
if (op == "==") return eq(a, b);
|
|
713
|
+
if (op == "!=") return !eq(a, b);
|
|
714
|
+
if (a is Money || b is Money)
|
|
715
|
+
{
|
|
716
|
+
Money m; object o; string o2;
|
|
717
|
+
if (a is Money am) { m = am; o = b; o2 = op; } else { m = (Money)b; o = a; o2 = flip(op); }
|
|
718
|
+
if (o == null) throw TypeErr("'" + o2 + "' not supported between instances of 'decimal.Decimal' and 'NoneType'");
|
|
719
|
+
return holds(o2, Dec.Cmp(m.amount, moneyOther(o, "compare")));
|
|
720
|
+
}
|
|
721
|
+
var c = order(a, b);
|
|
722
|
+
if (c == null) throw TypeErr("'" + op + "' not supported between instances of '" + typeName(a) + "' and '" + typeName(b) + "'");
|
|
723
|
+
return holds(op, c.Value);
|
|
724
|
+
}
|
|
725
|
+
static int? order(object a, object b)
|
|
726
|
+
{
|
|
727
|
+
if (isNumLike(a) && isNumLike(b)) return numCmp(a, b);
|
|
728
|
+
if (a is string sa && b is string sb) return cmpStr(sa, sb);
|
|
729
|
+
if (a is PyDate da && b is PyDate db) return Math.Sign(da.Num() - db.Num());
|
|
730
|
+
var seqA = a is List<object> la ? la : a is Tuple ta ? ta.items : null;
|
|
731
|
+
var seqB = b is List<object> lb ? lb : b is Tuple tb ? tb.items : null;
|
|
732
|
+
if (seqA != null && seqB != null && (a is List<object>) == (b is List<object>))
|
|
733
|
+
{
|
|
734
|
+
for (int i = 0; i < Math.Min(seqA.Count, seqB.Count); i++)
|
|
735
|
+
{
|
|
736
|
+
if (eq(seqA[i], seqB[i])) continue;
|
|
737
|
+
return compare("<", seqA[i], seqB[i]) ? -1 : 1;
|
|
738
|
+
}
|
|
739
|
+
return Math.Sign(seqA.Count - seqB.Count);
|
|
740
|
+
}
|
|
741
|
+
return null;
|
|
742
|
+
}
|
|
743
|
+
static int cmpStr(string a, string b)
|
|
744
|
+
{
|
|
745
|
+
var x = chars(a); var y = chars(b);
|
|
746
|
+
for (int i = 0; i < Math.Min(x.Count, y.Count); i++) { int d = cp(x[i]) - cp(y[i]); if (d != 0) return Math.Sign(d); }
|
|
747
|
+
return Math.Sign(x.Count - y.Count);
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
public static bool contains(object container, object item)
|
|
751
|
+
{
|
|
752
|
+
if (container is string s)
|
|
753
|
+
{
|
|
754
|
+
if (!(item is string si)) throw TypeErr("'in <string>' requires string as left operand, not " + typeName(item));
|
|
755
|
+
return s.Contains(si, StringComparison.Ordinal);
|
|
756
|
+
}
|
|
757
|
+
if (container is PyDict m) return m.Has(item);
|
|
758
|
+
if (container is List<object> l) return l.Any(x => same(x, item) || eq(x, item));
|
|
759
|
+
if (container is Tuple t) return t.items.Any(x => eq(x, item));
|
|
760
|
+
throw TypeErr("argument of type '" + typeName(container) + "' is not iterable");
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
sealed class Keyed { public object v; public object k; public int i; }
|
|
764
|
+
public static List<object> pySort(List<object> items, Func<object, object> key, bool reverse)
|
|
765
|
+
{
|
|
766
|
+
var keyed = items.Select((v, i) => new Keyed { v = v, k = key != null ? key(v) : v, i = i }).ToArray();
|
|
767
|
+
V8Sort.Sort(keyed, (x, y) =>
|
|
768
|
+
{
|
|
769
|
+
if (compare("<", reverse ? y.k : x.k, reverse ? x.k : y.k)) return -1;
|
|
770
|
+
if (compare("<", reverse ? x.k : y.k, reverse ? y.k : x.k)) return 1;
|
|
771
|
+
return x.i - y.i;
|
|
772
|
+
});
|
|
773
|
+
return keyed.Select(x => x.v).ToList();
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
public static PyErr attrErr(object v, string name) => new PyErr("AttributeError", "'" + typeName(v) + "' object has no attribute '" + name + "'");
|
|
777
|
+
public static string strMethod(object v, string name) { if (!(v is string s)) throw attrErr(v, name); return s; }
|
|
778
|
+
|
|
779
|
+
// ── JSON, the way Python's json module reads and writes it ──────────────────────────────────────────────────
|
|
780
|
+
sealed class JsonError : Exception { public int pos; public JsonError(string m, int p) : base(m) { pos = p; } }
|
|
781
|
+
static readonly System.Text.RegularExpressions.Regex JNUM = new System.Text.RegularExpressions.Regex(@"\G-?(?:0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?");
|
|
782
|
+
static bool isHex4(string s, int at) { if (at + 4 > s.Length) return false; for (int k = at; k < at + 4; k++) if (!Uri.IsHexDigit(s[k])) return false; return true; }
|
|
783
|
+
static string fromCodePoint(int c) => c >= 0xd800 && c <= 0xdfff ? ((char)c).ToString() : char.ConvertFromUtf32(c);
|
|
784
|
+
public static object jsonParse(string s)
|
|
785
|
+
{
|
|
786
|
+
int n = s.Length;
|
|
787
|
+
int ws(int i) { while (i < n && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r')) i++; return i; }
|
|
788
|
+
(string, int) str(int begin)
|
|
789
|
+
{
|
|
790
|
+
int i = begin + 1; var sb = new StringBuilder();
|
|
791
|
+
for (; ; )
|
|
792
|
+
{
|
|
793
|
+
if (i >= n) throw new JsonError("Unterminated string starting at", begin);
|
|
794
|
+
char ch = s[i];
|
|
795
|
+
if (ch == '"') return (sb.ToString(), i + 1);
|
|
796
|
+
if (ch < 0x20) throw new JsonError("Invalid control character at", i);
|
|
797
|
+
if (ch != '\\') { sb.Append(ch); i++; continue; }
|
|
798
|
+
if (i + 1 >= n) throw new JsonError("Unterminated string starting at", begin);
|
|
799
|
+
char esc = s[i + 1];
|
|
800
|
+
string simple = esc == '"' ? "\"" : esc == '\\' ? "\\" : esc == '/' ? "/" : esc == 'b' ? "\b" : esc == 'f' ? "\f" : esc == 'n' ? "\n" : esc == 'r' ? "\r" : esc == 't' ? "\t" : null;
|
|
801
|
+
if (simple != null) { sb.Append(simple); i += 2; continue; }
|
|
802
|
+
if (esc != 'u') throw new JsonError("Invalid \\escape", i);
|
|
803
|
+
if (!isHex4(s, i + 2)) throw new JsonError("Invalid \\uXXXX escape", i + 1);
|
|
804
|
+
int c = Convert.ToInt32(s.Substring(i + 2, 4), 16);
|
|
805
|
+
i += 6;
|
|
806
|
+
if (c >= 0xd800 && c <= 0xdbff && i + 1 < n && s[i] == '\\' && s[i + 1] == 'u' && isHex4(s, i + 2))
|
|
807
|
+
{
|
|
808
|
+
int lo = Convert.ToInt32(s.Substring(i + 2, 4), 16);
|
|
809
|
+
if (lo >= 0xdc00 && lo <= 0xdfff) { c = 0x10000 + ((c - 0xd800) << 10) + (lo - 0xdc00); i += 6; }
|
|
810
|
+
}
|
|
811
|
+
sb.Append(fromCodePoint(c));
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
(object, int) value(int i)
|
|
815
|
+
{
|
|
816
|
+
if (i >= n) throw new JsonError("Expecting value", i);
|
|
817
|
+
char ch = s[i];
|
|
818
|
+
if (ch == '"') { var (v, e) = str(i); return (v, e); }
|
|
819
|
+
if (ch == '{') return obj(i + 1);
|
|
820
|
+
if (ch == '[') return arr(i + 1);
|
|
821
|
+
if (string.CompareOrdinal(s, i, "null", 0, 4) == 0) return (null, i + 4);
|
|
822
|
+
if (string.CompareOrdinal(s, i, "true", 0, 4) == 0) return (true, i + 4);
|
|
823
|
+
if (string.CompareOrdinal(s, i, "false", 0, 5) == 0) return (false, i + 5);
|
|
824
|
+
var m = JNUM.Match(s, i);
|
|
825
|
+
if (m.Success && m.Index == i && m.Length > 0)
|
|
826
|
+
{
|
|
827
|
+
if (m.Groups[1].Success || m.Groups[2].Success) return (Dec.Parse(m.Value), i + m.Length);
|
|
828
|
+
return (BigInteger.Parse(m.Value), i + m.Length);
|
|
829
|
+
}
|
|
830
|
+
throw new JsonError("Expecting value", i);
|
|
831
|
+
}
|
|
832
|
+
(object, int) obj(int i)
|
|
833
|
+
{
|
|
834
|
+
var d = new PyDict();
|
|
835
|
+
i = ws(i);
|
|
836
|
+
if (i < n && s[i] == '}') return (d, i + 1);
|
|
837
|
+
for (; ; )
|
|
838
|
+
{
|
|
839
|
+
if (i >= n || s[i] != '"') throw new JsonError("Expecting property name enclosed in double quotes", i);
|
|
840
|
+
var (k, i2) = str(i); i = ws(i2);
|
|
841
|
+
if (i >= n || s[i] != ':') throw new JsonError("Expecting ':' delimiter", i);
|
|
842
|
+
i = ws(i + 1);
|
|
843
|
+
var (v, i3) = value(i); i = i3;
|
|
844
|
+
d.Set(k, v);
|
|
845
|
+
i = ws(i);
|
|
846
|
+
if (i < n && s[i] == '}') return (d, i + 1);
|
|
847
|
+
if (i >= n || s[i] != ',') throw new JsonError("Expecting ',' delimiter", i);
|
|
848
|
+
int comma = i;
|
|
849
|
+
i = ws(i + 1);
|
|
850
|
+
if (i < n && s[i] == '}') throw new JsonError("Illegal trailing comma before end of object", comma);
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
(object, int) arr(int i)
|
|
854
|
+
{
|
|
855
|
+
var out_ = new List<object>();
|
|
856
|
+
i = ws(i);
|
|
857
|
+
if (i < n && s[i] == ']') return (out_, i + 1);
|
|
858
|
+
for (; ; )
|
|
859
|
+
{
|
|
860
|
+
var (v, i2) = value(i); i = i2;
|
|
861
|
+
out_.Add(v);
|
|
862
|
+
i = ws(i);
|
|
863
|
+
if (i < n && s[i] == ']') return (out_, i + 1);
|
|
864
|
+
if (i >= n || s[i] != ',') throw new JsonError("Expecting ',' delimiter", i);
|
|
865
|
+
int comma = i;
|
|
866
|
+
i = ws(i + 1);
|
|
867
|
+
if (i < n && s[i] == ']') throw new JsonError("Illegal trailing comma before end of array", comma);
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
try
|
|
871
|
+
{
|
|
872
|
+
var (v, end) = value(ws(0));
|
|
873
|
+
end = ws(end);
|
|
874
|
+
if (end != n) throw new JsonError("Extra data", end);
|
|
875
|
+
return v;
|
|
876
|
+
}
|
|
877
|
+
catch (JsonError e)
|
|
878
|
+
{
|
|
879
|
+
var before = s.Substring(0, Math.Min(e.pos, s.Length));
|
|
880
|
+
int line = before.Count(ch => ch == '\n') + 1;
|
|
881
|
+
int col = e.pos - before.LastIndexOf('\n');
|
|
882
|
+
throw ConversionFailed("This is not JSON: " + e.Message + " (line " + line + ", column " + col + ").");
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
static object jsonReady(object v)
|
|
886
|
+
{
|
|
887
|
+
if (v == null || v is bool || v is string || v is BigInteger || v is Dec) return v;
|
|
888
|
+
if (v is Money) throw KindMismatch("Money has no JSON form of its own: use its amount, for example price's amount.");
|
|
889
|
+
if (v is List<object> l) return l.Select(jsonReady).ToList();
|
|
890
|
+
if (v is Tuple t) return t.items.Select(jsonReady).ToList();
|
|
891
|
+
if (v is PyDict m)
|
|
892
|
+
{
|
|
893
|
+
var out_ = new PyDict();
|
|
894
|
+
foreach (var e in m.Entries()) { if (!(e[0] is string)) throw KindMismatch("A JSON object's keys are text, but one is " + describe(e[0]) + "."); out_.Set(e[0], jsonReady(e[1])); }
|
|
895
|
+
return out_;
|
|
896
|
+
}
|
|
897
|
+
if (v is RecordVal r) { var out_ = new PyDict(); foreach (var f in r.cls.fields) out_.Set(f.py, jsonReady(r.f.TryGetValue(f.py, out var x) ? x : null)); return out_; }
|
|
898
|
+
throw KindMismatch(describe(v) + " has no JSON form.");
|
|
899
|
+
}
|
|
900
|
+
static string jsonStr(string s)
|
|
901
|
+
{
|
|
902
|
+
var sb = new StringBuilder("\"");
|
|
903
|
+
foreach (var ch in chars(s))
|
|
904
|
+
{
|
|
905
|
+
int c = cp(ch);
|
|
906
|
+
if (ch == "\"") sb.Append("\\\"");
|
|
907
|
+
else if (ch == "\\") sb.Append("\\\\");
|
|
908
|
+
else if (ch == "\n") sb.Append("\\n");
|
|
909
|
+
else if (ch == "\r") sb.Append("\\r");
|
|
910
|
+
else if (ch == "\t") sb.Append("\\t");
|
|
911
|
+
else if (ch == "\b") sb.Append("\\b");
|
|
912
|
+
else if (ch == "\f") sb.Append("\\f");
|
|
913
|
+
else if (c >= 0x20 && c <= 0x7e) sb.Append(ch);
|
|
914
|
+
else if (c > 0xffff) { int v = c - 0x10000; sb.Append("\\u").Append((0xd800 + (v >> 10)).ToString("x")).Append("\\u").Append((0xdc00 + (v & 0x3ff)).ToString("x")); }
|
|
915
|
+
else sb.Append("\\u").Append(c.ToString("x4"));
|
|
916
|
+
}
|
|
917
|
+
return sb.Append('"').ToString();
|
|
918
|
+
}
|
|
919
|
+
public static string jsonText(object v)
|
|
920
|
+
{
|
|
921
|
+
string w(object x)
|
|
922
|
+
{
|
|
923
|
+
if (x == null) return "null";
|
|
924
|
+
if (x is bool b) return b ? "true" : "false";
|
|
925
|
+
if (x is BigInteger i) return i.ToString();
|
|
926
|
+
if (x is Dec d) { var t = d.ToString(); return d.IsIntegral() && t.Contains('E') ? d.ToFixed() : t; }
|
|
927
|
+
if (x is string s) return jsonStr(s);
|
|
928
|
+
if (x is List<object> l) return "[" + string.Join(", ", l.Select(w)) + "]";
|
|
929
|
+
var m = (PyDict)x;
|
|
930
|
+
return "{" + string.Join(", ", m.Entries().Select(e => jsonStr((string)e[0]) + ": " + w(e[1]))) + "}";
|
|
931
|
+
}
|
|
932
|
+
return w(jsonReady(v));
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
// ── Helpers the generated code calls ─────────────────────────────────────────────────────────────────────
|
|
936
|
+
public static object I(string text) => BigInteger.Parse(text);
|
|
937
|
+
public static object dec(string text) => Dec.Parse(text);
|
|
938
|
+
public static object money(string text) => Money.Of(text);
|
|
939
|
+
public static object today() => PyDate.Today();
|
|
940
|
+
public static object date(string text) { var d = PyDate.Parse(text); if (d == null) throw new PyErr("ValueError", "Invalid isoformat string: '" + text + "'"); return d; }
|
|
941
|
+
public static object newMap() => new PyDict();
|
|
942
|
+
public static object list(params object[] items) => items == null ? new List<object> { null } : new List<object>(items);
|
|
943
|
+
public static List<object> filter(IEnumerable<object> items, Func<object, bool> keep) { var out_ = new List<object>(); foreach (var x in items) if (keep(x)) out_.Add(x); return out_; }
|
|
944
|
+
public static List<object> map(IEnumerable<object> items, Func<object, object> get) { var out_ = new List<object>(); foreach (var x in items) out_.Add(get(x)); return out_; }
|
|
945
|
+
public static void discard(object v) { }
|
|
946
|
+
public static bool at(Frame F, int line) { F.line = line; return true; }
|
|
947
|
+
|
|
948
|
+
public static BigInteger rangeInt(object v)
|
|
949
|
+
{
|
|
950
|
+
if (v is BigInteger i) return i;
|
|
951
|
+
if (v is bool b) return b ? BigInteger.One : BigInteger.Zero;
|
|
952
|
+
throw TypeErr("'" + (v is Dec ? "decimal.Decimal" : v == null ? "NoneType" : v is Money ? "Money" : v is string ? "str" : "object") + "' object cannot be interpreted as an integer");
|
|
953
|
+
}
|
|
954
|
+
public static List<object> unpack2(object el)
|
|
955
|
+
{
|
|
956
|
+
List<object> items = el is List<object> l ? l : el is Tuple t ? t.items : el is string s ? chars(s).Cast<object>().ToList() : el is PyDict m ? m.Keys() : null;
|
|
957
|
+
if (items == null) throw TypeErr("cannot unpack non-iterable " + (el == null ? "NoneType" : isInt(el) ? "int" : el is Dec ? "decimal.Decimal" : el is bool ? "bool" : "object") + " object");
|
|
958
|
+
if (items.Count < 2) throw new PyErr("ValueError", "not enough values to unpack (expected 2, got " + items.Count + ")");
|
|
959
|
+
if (items.Count > 2) throw new PyErr("ValueError", "too many values to unpack (expected 2, got " + items.Count + ")");
|
|
960
|
+
return items;
|
|
961
|
+
}
|
|
962
|
+
public static List<object> mapItems(object m) { if (!(m is PyDict d)) throw attrErr(m, "items"); return d.Items(); }
|
|
963
|
+
public static List<object> pairsOf(object c) => c is PyDict d ? d.Items() : pyList(c);
|
|
964
|
+
public static object tupleAt(object t, int i) => ((Tuple)t).items[i];
|
|
965
|
+
|
|
966
|
+
static readonly object NO_DEFAULT = new object();
|
|
967
|
+
public static object itemAt(object items, object position) => itemAt(items, position, NO_DEFAULT);
|
|
968
|
+
public static object itemAt(object items, object position, object dflt)
|
|
969
|
+
{
|
|
970
|
+
if (!(position is BigInteger pos)) throw KindMismatch("A position in a list is a whole number, not " + describe(position) + ".");
|
|
971
|
+
var list_ = items is List<object> l ? l : items is Tuple t ? t.items : null;
|
|
972
|
+
if (list_ == null) throw TypeErr("object of type '" + (items == null ? "NoneType" : "object") + "' has no len()");
|
|
973
|
+
if (pos >= 1 && pos <= list_.Count) return list_[(int)pos - 1];
|
|
974
|
+
if (!ReferenceEquals(dflt, NO_DEFAULT)) return dflt;
|
|
975
|
+
throw MissingValue("There is no item " + pos + ": the list has " + list_.Count + " item" + (list_.Count == 1 ? "" : "s") + ".");
|
|
976
|
+
}
|
|
977
|
+
public static void setItem(object items, object position, object value) { itemAt(items, position); ((List<object>)items)[(int)(BigInteger)position - 1] = value; }
|
|
978
|
+
public static void mapSet(object m, object k, object v)
|
|
979
|
+
{
|
|
980
|
+
if (m is PyDict d) { d.Set(k, v); return; }
|
|
981
|
+
if (m == null) throw TypeErr("'NoneType' object does not support item assignment");
|
|
982
|
+
if (m is List<object>) { setItem(m, k, v); return; }
|
|
983
|
+
throw TypeErr("'" + (m is Money ? "Money" : "object") + "' object does not support item assignment");
|
|
984
|
+
}
|
|
985
|
+
public static void setEntry(object c, object k, object v)
|
|
986
|
+
{
|
|
987
|
+
if (c is List<object>) setItem(c, k, v);
|
|
988
|
+
else if (c is PyDict d) d.Set(k, v);
|
|
989
|
+
else if (c == null) throw MissingValue("This value is nothing, so it has no entry for " + show(k) + ".");
|
|
990
|
+
else throw KindMismatch(describe(c) + " has no entries that can be changed.");
|
|
991
|
+
}
|
|
992
|
+
public static object entry(object c, object k) => entry(c, k, NO_DEFAULT);
|
|
993
|
+
public static object entry(object c, object k, object dflt)
|
|
994
|
+
{
|
|
995
|
+
if (c is List<object> || c is Tuple) return itemAt(c, k, dflt);
|
|
996
|
+
if (c is PyDict d) { if (d.Has(k)) return d.Get(k); if (!ReferenceEquals(dflt, NO_DEFAULT)) return dflt; throw MissingValue("There is no entry for " + show(k) + "."); }
|
|
997
|
+
if (c == null) throw MissingValue("This value is nothing, so it has no entry for " + show(k) + ".");
|
|
998
|
+
throw KindMismatch(describe(c) + " has no entries.");
|
|
999
|
+
}
|
|
1000
|
+
public static object mapGet(object m, object k) => mapGet(m, k, NO_DEFAULT);
|
|
1001
|
+
public static object mapGet(object m, object k, object dflt)
|
|
1002
|
+
{
|
|
1003
|
+
bool has = !ReferenceEquals(dflt, NO_DEFAULT);
|
|
1004
|
+
if (m is PyDict d) { if (d.Has(k)) return d.Get(k); if (has) return dflt; throw new PyErr("KeyError", pyStr(k), new[] { k }); }
|
|
1005
|
+
if (m == null) throw has ? (Exception)attrErr(m, "get") : TypeErr("'NoneType' object is not subscriptable");
|
|
1006
|
+
if (has) throw attrErr(m, "get");
|
|
1007
|
+
if (m is List<object> l)
|
|
1008
|
+
{
|
|
1009
|
+
if (k is BigInteger kb && kb >= -l.Count && kb < l.Count) { int i = (int)kb; return l[i < 0 ? l.Count + i : i]; }
|
|
1010
|
+
throw new PyErr("IndexError", "list index out of range");
|
|
1011
|
+
}
|
|
1012
|
+
throw TypeErr("'" + (m is Money ? "Money" : "object") + "' object is not subscriptable");
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
public static object getAttr(object obj, string name)
|
|
1016
|
+
{
|
|
1017
|
+
if (obj is RecordVal r && r.f.ContainsKey(name)) return r.f[name];
|
|
1018
|
+
if (obj is Money m && name == "amount") return m.amount;
|
|
1019
|
+
throw attrErr(obj, name);
|
|
1020
|
+
}
|
|
1021
|
+
public static void setAttr(object obj, string name, object value)
|
|
1022
|
+
{
|
|
1023
|
+
if (obj is RecordVal rec)
|
|
1024
|
+
{
|
|
1025
|
+
if (rec.cls.rules != null && rec.cls.rules.TryGetValue(name, out var rs)) foreach (var r in rs) never(r.cond(value), r.text, r.line, value);
|
|
1026
|
+
rec.f[name] = value; return;
|
|
1027
|
+
}
|
|
1028
|
+
if (obj is Money) throw new PyErr("AttributeError", "Money cannot be changed; make new money instead.");
|
|
1029
|
+
throw attrErr(obj, name);
|
|
1030
|
+
}
|
|
1031
|
+
static string[] fieldNames(string key) => new[] { key, key.Replace(" ", "_"), key.ToLowerInvariant(), key.ToLowerInvariant().Replace(" ", "_") };
|
|
1032
|
+
public static object getField(object obj, string key)
|
|
1033
|
+
{
|
|
1034
|
+
if (obj == null) throw MissingValue("This value is nothing, so it has no " + key + ".");
|
|
1035
|
+
var names = fieldNames(key);
|
|
1036
|
+
if (obj is PyDict d)
|
|
1037
|
+
{
|
|
1038
|
+
foreach (var k in names) if (d.Has(k)) return d.Get(k);
|
|
1039
|
+
foreach (var e in d.Entries()) if (pyStrip(pyStr(e[0])).ToLowerInvariant() == key.ToLowerInvariant()) return e[1];
|
|
1040
|
+
throw MissingValue("There is no field \"" + key + "\". Fields here: " + string.Join(", ", d.Keys().Select(pyStr)) + ".");
|
|
1041
|
+
}
|
|
1042
|
+
foreach (var k in names)
|
|
1043
|
+
{
|
|
1044
|
+
if (obj is RecordVal r && r.f.ContainsKey(k)) return r.f[k];
|
|
1045
|
+
if (obj is Money m && k == "amount") return m.amount;
|
|
1046
|
+
}
|
|
1047
|
+
throw MissingValue(describe(obj) + " has no field \"" + key + "\".");
|
|
1048
|
+
}
|
|
1049
|
+
public static void setField(object obj, string key, object value)
|
|
1050
|
+
{
|
|
1051
|
+
if (obj is PyDict d) { d.Set(key, value); return; }
|
|
1052
|
+
foreach (var k in fieldNames(key)) if (obj is RecordVal r && r.f.ContainsKey(k)) { setAttr(obj, k, value); return; }
|
|
1053
|
+
throw MissingValue(describe(obj) + " has no field \"" + key + "\".");
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
public static object addTo(object target, object value) { if (target is List<object> l) { l.Add(value); return l; } return add(target, value); }
|
|
1057
|
+
public static void appendTo(object target, object value) { if (!(target is List<object> l)) throw attrErr(target, "append"); l.Add(value); }
|
|
1058
|
+
public static void removeFrom(object target, object value)
|
|
1059
|
+
{
|
|
1060
|
+
if (target is PyDict d) { if (!d.Has(value)) throw MissingValue("There is no entry for " + show(value) + " to remove."); d.Delete(value); return; }
|
|
1061
|
+
if (!contains(target, value)) throw MissingValue(show(value) + " is not in the list, so it can't be removed.");
|
|
1062
|
+
if (!(target is List<object> l)) throw attrErr(target, "remove");
|
|
1063
|
+
l.RemoveAt(l.FindIndex(x => same(x, value) || eq(x, value)));
|
|
1064
|
+
}
|
|
1065
|
+
public static void sortInPlace(object target, Func<object, object> key, bool desc)
|
|
1066
|
+
{
|
|
1067
|
+
if (!(target is List<object> l)) throw attrErr(target, "sort");
|
|
1068
|
+
var sorted = pySort(l, key, desc);
|
|
1069
|
+
l.Clear(); l.AddRange(sorted);
|
|
1070
|
+
}
|
|
1071
|
+
public static void reverseInPlace(object target) { if (!(target is List<object> l)) throw attrErr(target, "reverse"); l.Reverse(); }
|
|
1072
|
+
|
|
1073
|
+
public static RecordKind recordKind(string py, FieldDef[] fields, Dictionary<string, Rule[]> rules = null) => new RecordKind { py = py, fields = fields.ToList(), rules = rules ?? new Dictionary<string, Rule[]>() };
|
|
1074
|
+
public static FieldDef field(string py, string k) => new FieldDef(py, k);
|
|
1075
|
+
public static object newRecord(object kind, params object[] pairs)
|
|
1076
|
+
{
|
|
1077
|
+
var cls = (RecordKind)kind;
|
|
1078
|
+
var given = new Dictionary<string, object>();
|
|
1079
|
+
for (int i = 0; i + 1 < pairs.Length; i += 2) given[(string)pairs[i]] = pairs[i + 1];
|
|
1080
|
+
var rec = new RecordVal(cls);
|
|
1081
|
+
var missing = cls.fields.Where(f => !given.ContainsKey(f.py) && f.k != "optional" && f.k != "list" && f.k != "map").ToList();
|
|
1082
|
+
if (missing.Count > 0) throw TypeErr(cls.py + ".__init__() missing " + missing.Count + " required keyword-only argument" + (missing.Count == 1 ? "" : "s") + ": " + string.Join(missing.Count == 2 ? " and " : ", ", missing.Select(f => "'" + f.py + "'")));
|
|
1083
|
+
foreach (var f in cls.fields)
|
|
1084
|
+
{
|
|
1085
|
+
object v = given.ContainsKey(f.py) ? given[f.py] : f.k == "optional" ? null : f.k == "list" ? new List<object>() : (object)new PyDict();
|
|
1086
|
+
setAttr(rec, f.py, v);
|
|
1087
|
+
}
|
|
1088
|
+
return rec;
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
public static void never(object cond, string text, int line, object value)
|
|
1092
|
+
{
|
|
1093
|
+
if (truthy(cond)) throw RuleBroken(text + " (the rule on line " + line + "), but the value is " + show(value) + ".");
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
public static object applyOp(string op, object a)
|
|
1097
|
+
{
|
|
1098
|
+
switch (op)
|
|
1099
|
+
{
|
|
1100
|
+
case "sum": return totalOf(pyList(a));
|
|
1101
|
+
case "average": { var items = pyList(a); if (items.Count == 0) throw MissingValue("I can't take the average of an empty list."); return divide(totalOf(items), new BigInteger(items.Count)); }
|
|
1102
|
+
case "count": case "length": return pyLen(a);
|
|
1103
|
+
case "min": { var items = pyList(a); if (items.Count == 0) throw MissingValue("An empty list has no smallest item."); var best = items[0]; for (int i = 1; i < items.Count; i++) if (compare("<", items[i], best)) best = items[i]; return best; }
|
|
1104
|
+
case "max": { var items = pyList(a); if (items.Count == 0) throw MissingValue("An empty list has no largest item."); var best = items[0]; for (int i = 1; i < items.Count; i++) if (compare(">", items[i], best)) best = items[i]; return best; }
|
|
1105
|
+
case "first": { var items = pyList(a); if (items.Count == 0) throw MissingValue("An empty list has no first item."); return items[0]; }
|
|
1106
|
+
case "last": { var items = pyList(a); if (items.Count == 0) throw MissingValue("An empty list has no last item."); return items[items.Count - 1]; }
|
|
1107
|
+
case "words": return pySplit(pyStr(a)).Select(p => (object)stripPunct((string)p)).Where(p => (string)p != "").ToList();
|
|
1108
|
+
case "lines": return splitLines(strMethod(a, "splitlines"));
|
|
1109
|
+
case "lowercase": return jsLower(strMethod(a, "lower"));
|
|
1110
|
+
case "uppercase": return jsUpper(strMethod(a, "upper"));
|
|
1111
|
+
case "trimmed": return pyStrip(strMethod(a, "strip"));
|
|
1112
|
+
case "parts": return pySplit(textOf(a, "\"the parts of\""));
|
|
1113
|
+
case "abs":
|
|
1114
|
+
{
|
|
1115
|
+
if (a is Money m) return new Money(m.amount.Abs());
|
|
1116
|
+
if (a is bool || !isNumber(a)) throw KindMismatch("\"the absolute value of\" needs a number or money, but it is " + describe(a) + ".");
|
|
1117
|
+
return a is BigInteger i ? (object)BigInteger.Abs(i) : ((Dec)a).Abs();
|
|
1118
|
+
}
|
|
1119
|
+
case "jsonText": return jsonText(a);
|
|
1120
|
+
case "jsonData": return jsonParse(textOf(a, "\"the JSON data in\""));
|
|
1121
|
+
case "keys": if (!(a is PyDict dk)) throw attrErr(a, "keys"); return dk.Keys();
|
|
1122
|
+
case "values": if (!(a is PyDict dv)) throw attrErr(a, "values"); return dv.Values();
|
|
1123
|
+
default: throw new PyErr("NameError", "name '" + op + "' is not defined");
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
public static bool affix(object t, object a, bool end)
|
|
1127
|
+
{
|
|
1128
|
+
var what = end ? "\"ends with\"" : "\"starts with\"";
|
|
1129
|
+
var ts = textOf(t, what); var as_ = textOf(a, what);
|
|
1130
|
+
return end ? ts.EndsWith(as_, StringComparison.Ordinal) : ts.StartsWith(as_, StringComparison.Ordinal);
|
|
1131
|
+
}
|
|
1132
|
+
public static bool between(object lo, object v, Func<object> hi) { if (!compare("<=", lo, v)) return false; return compare("<=", v, hi()); }
|
|
1133
|
+
public static bool isIn(object item, object container) => contains(container, item);
|
|
1134
|
+
|
|
1135
|
+
public static object readText(object path)
|
|
1136
|
+
{
|
|
1137
|
+
if (!(path is string p)) throw TypeErr("expected str, bytes or os.PathLike object, not " + (path == null ? "NoneType" : "object"));
|
|
1138
|
+
var full = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), p));
|
|
1139
|
+
if (Directory.Exists(full)) throw new PyErr("IsADirectoryError", "EISDIR: illegal operation on a directory, read");
|
|
1140
|
+
if (!File.Exists(full)) throw MissingValue("There is no file \"" + p + "\" (looked in the folder the program runs in).");
|
|
1141
|
+
try { return new UTF8Encoding(false).GetString(File.ReadAllBytes(full)); }
|
|
1142
|
+
catch (Exception e) { throw new PyErr("OSError", e.Message); }
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
public static void expectTrue(object v, string text) { if (!(v is bool b && b)) throw ExpectationFailed(text + ", but it was not true."); }
|
|
1146
|
+
public static void expectFailure(Action run, string text, object msg)
|
|
1147
|
+
{
|
|
1148
|
+
try { run(); }
|
|
1149
|
+
catch (Exception e)
|
|
1150
|
+
{
|
|
1151
|
+
var err = asPyErr(e);
|
|
1152
|
+
if (err.thunder && msg != null)
|
|
1153
|
+
{
|
|
1154
|
+
if (!(msg is string ms)) throw TypeErr("'in <string>' requires string as left operand, not " + (msg is BigInteger ? "int" : "object"));
|
|
1155
|
+
if (!err.Message.Contains(ms, StringComparison.Ordinal)) throw ExpectationFailed(text + ", but it failed with \"" + err.Message + "\".");
|
|
1156
|
+
}
|
|
1157
|
+
return;
|
|
1158
|
+
}
|
|
1159
|
+
throw ExpectationFailed(text + ", but it did not fail.");
|
|
1160
|
+
}
|
|
1161
|
+
static readonly Dictionary<string, Func<object, object, bool>> CHECKS = new Dictionary<string, Func<object, object, bool>>
|
|
1162
|
+
{
|
|
1163
|
+
["is"] = (a, b) => eq(a, b),
|
|
1164
|
+
["is not"] = (a, b) => !eq(a, b),
|
|
1165
|
+
["at least"] = (a, b) => compare(">=", a, b),
|
|
1166
|
+
["at most"] = (a, b) => compare("<=", a, b),
|
|
1167
|
+
["more than"] = (a, b) => compare(">", a, b),
|
|
1168
|
+
["less than"] = (a, b) => compare("<", a, b),
|
|
1169
|
+
["nothing"] = (a, b) => a == null,
|
|
1170
|
+
["not nothing"] = (a, b) => a != null,
|
|
1171
|
+
["empty"] = (a, b) => eq(pyLen(a), BigInteger.Zero),
|
|
1172
|
+
["positive"] = (a, b) => compare(">", a, BigInteger.Zero),
|
|
1173
|
+
["negative"] = (a, b) => compare("<", a, BigInteger.Zero),
|
|
1174
|
+
["zero"] = (a, b) => eq(a, BigInteger.Zero),
|
|
1175
|
+
["between"] = (a, b) => compare("<=", ((List<object>)b)[0], a) && compare("<=", a, ((List<object>)b)[1]),
|
|
1176
|
+
["in"] = (a, b) => contains(b, a),
|
|
1177
|
+
["contains"] = (a, b) => contains(a, b),
|
|
1178
|
+
};
|
|
1179
|
+
public static void expectValue(object actual, string full, string op, object want, string text)
|
|
1180
|
+
{
|
|
1181
|
+
bool ok = CHECKS.TryGetValue(full, out var known) ? known(actual, want) : !CHECKS[op](actual, want);
|
|
1182
|
+
if (!ok) throw ExpectationFailed(text + ", but it was " + show(actual) + ".");
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
public static string describeError(TErr e)
|
|
1186
|
+
{
|
|
1187
|
+
var where_ = e.where ?? new List<Where>();
|
|
1188
|
+
var inner = where_.Count > 0 ? where_[where_.Count - 1] : null;
|
|
1189
|
+
var message = explain(e);
|
|
1190
|
+
var code = codeOf(e);
|
|
1191
|
+
if (code == "TC508" && !e.thunder) message = "Python code used by this line failed: " + message;
|
|
1192
|
+
var place = inner != null ? inner.file + ", line " + inner.line : "In the program";
|
|
1193
|
+
var callers = where_.Take(Math.Max(0, where_.Count - 1)).Select(f => f.line.ToString()).ToList();
|
|
1194
|
+
if (callers.Count > 0 && inner != null) { callers.Reverse(); place += " (reached from line " + string.Join(", then line ", callers) + ")"; }
|
|
1195
|
+
return place + ": " + message + " [" + code + "]";
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
// ── conversions and text helpers ────────────────────────────────────────────────────────────────────────────
|
|
1199
|
+
static readonly System.Text.RegularExpressions.Regex NUMBER = new System.Text.RegularExpressions.Regex(@"^[+-]?([0-9][0-9_]*)(\.[0-9]+)?$");
|
|
1200
|
+
public static object toNumber(object x)
|
|
1201
|
+
{
|
|
1202
|
+
if (isNumber(x)) return x;
|
|
1203
|
+
if (x is Money m) return m.amount;
|
|
1204
|
+
if (x is string str)
|
|
1205
|
+
{
|
|
1206
|
+
var s = pyStrip(str).Replace(",", "");
|
|
1207
|
+
if (NUMBER.IsMatch(s)) return s.Contains('.') ? (object)Dec.Parse(s) : BigInteger.Parse(s.Replace("_", ""));
|
|
1208
|
+
}
|
|
1209
|
+
throw ConversionFailed(describe(x) + " is not a number.");
|
|
1210
|
+
}
|
|
1211
|
+
public static object toWhole(object x)
|
|
1212
|
+
{
|
|
1213
|
+
var n = toNumber(x);
|
|
1214
|
+
if (n is BigInteger) return n;
|
|
1215
|
+
var d = (Dec)n;
|
|
1216
|
+
if (d.IsIntegral()) return d.ToBigInt();
|
|
1217
|
+
throw ConversionFailed(show(d) + " is not a whole number.");
|
|
1218
|
+
}
|
|
1219
|
+
public static object toMoney(object x)
|
|
1220
|
+
{
|
|
1221
|
+
if (x is Money) return x;
|
|
1222
|
+
if (x is string str)
|
|
1223
|
+
{
|
|
1224
|
+
var s = pyStrip(str).Replace(",", "");
|
|
1225
|
+
bool negative = s.StartsWith("-");
|
|
1226
|
+
s = s.TrimStart('-').TrimStart('$');
|
|
1227
|
+
if (NUMBER.IsMatch(s)) return Money.Of((negative ? "-" : "") + s);
|
|
1228
|
+
throw ConversionFailed(describe(x) + " is not an amount of money.");
|
|
1229
|
+
}
|
|
1230
|
+
return new Money(toDec(toNumber(x)));
|
|
1231
|
+
}
|
|
1232
|
+
public static object toYesNo(object x)
|
|
1233
|
+
{
|
|
1234
|
+
if (x is bool) return x;
|
|
1235
|
+
if (x is string s) { var t = pyStrip(s).ToLowerInvariant(); if (t == "yes" || t == "true") return true; if (t == "no" || t == "false") return false; }
|
|
1236
|
+
throw ConversionFailed(describe(x) + " is not yes or no.");
|
|
1237
|
+
}
|
|
1238
|
+
public static object toDate(object x)
|
|
1239
|
+
{
|
|
1240
|
+
if (x is PyDate) return x;
|
|
1241
|
+
var d = PyDate.Parse(pyStrip(pyStr(x)));
|
|
1242
|
+
if (d != null) return d;
|
|
1243
|
+
throw ConversionFailed(describe(x) + " is not a date (write it as YYYY-MM-DD).");
|
|
1244
|
+
}
|
|
1245
|
+
public static object totalOf(List<object> items)
|
|
1246
|
+
{
|
|
1247
|
+
if (items.Count == 0) return BigInteger.Zero;
|
|
1248
|
+
var result = items[0];
|
|
1249
|
+
for (int i = 1; i < items.Count; i++) result = add(result, items[i]);
|
|
1250
|
+
return result;
|
|
1251
|
+
}
|
|
1252
|
+
public static string textOf(object v, string what)
|
|
1253
|
+
{
|
|
1254
|
+
if (!(v is string s)) throw KindMismatch(what + " needs text, but it is " + describe(v) + ".");
|
|
1255
|
+
return s;
|
|
1256
|
+
}
|
|
1257
|
+
public static object joined(object items, object sep)
|
|
1258
|
+
{
|
|
1259
|
+
var sp = textOf(sep, "\"joined with\"");
|
|
1260
|
+
var out_ = new List<string>(); int i = 0;
|
|
1261
|
+
foreach (var x in pyIter(items))
|
|
1262
|
+
{
|
|
1263
|
+
if (!(x is string s)) throw KindMismatch("\"joined with\" joins text, but item " + (i + 1) + " is " + describe(x) + ". Turn it into text first.");
|
|
1264
|
+
out_.Add(s); i++;
|
|
1265
|
+
}
|
|
1266
|
+
return string.Join(sp, out_);
|
|
1267
|
+
}
|
|
1268
|
+
public static object splitAt(object text, object sep)
|
|
1269
|
+
{
|
|
1270
|
+
var sp = textOf(sep, "\"split at\"");
|
|
1271
|
+
if (sp == "") throw KindMismatch("\"split at\" needs something to split at, not empty text.");
|
|
1272
|
+
return textOf(text, "\"split at\"").Split(sp).Cast<object>().ToList();
|
|
1273
|
+
}
|
|
1274
|
+
public static object replacing(object text, object old, object nw)
|
|
1275
|
+
{
|
|
1276
|
+
var o = textOf(old, "\"replacing\"");
|
|
1277
|
+
if (o == "") throw KindMismatch("\"replacing\" needs something to replace, not empty text.");
|
|
1278
|
+
var t = textOf(text, "\"replacing\"");
|
|
1279
|
+
return string.Join(textOf(nw, "\"replacing … with\""), t.Split(o));
|
|
1280
|
+
}
|
|
1281
|
+
static readonly HashSet<string> PUNCT = new HashSet<string>(chars(".,;:!?\"'()[]{}<>“”‘’…-"));
|
|
1282
|
+
public static string stripPunct(string w)
|
|
1283
|
+
{
|
|
1284
|
+
var a = chars(w); int i = 0, j = a.Count;
|
|
1285
|
+
while (i < j && PUNCT.Contains(a[i])) i++;
|
|
1286
|
+
while (j > i && PUNCT.Contains(a[j - 1])) j--;
|
|
1287
|
+
return string.Concat(a.Skip(i).Take(j - i));
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
// ── Running compiled C#: frames (for error lines), output, and the program or its tests ────────────────────
|
|
1291
|
+
static readonly List<Frame> frames = new List<Frame>();
|
|
1292
|
+
static bool aborted;
|
|
1293
|
+
static StreamWriter stdout, stderr;
|
|
1294
|
+
static int exitCode;
|
|
1295
|
+
static List<Where> snapshot() => frames.Select(f => new Where(f.file, f.line)).ToList();
|
|
1296
|
+
|
|
1297
|
+
public static Frame enterFrame(string file, int line)
|
|
1298
|
+
{
|
|
1299
|
+
if (frames.Count >= MAX_FRAMES) throw new PyErr("RecursionError", "maximum recursion depth exceeded");
|
|
1300
|
+
var f = new Frame(file, line); frames.Add(f); return f;
|
|
1301
|
+
}
|
|
1302
|
+
public static Frame enterCall(string file, int line, int first)
|
|
1303
|
+
{
|
|
1304
|
+
if (frames.Count >= MAX_FRAMES)
|
|
1305
|
+
{
|
|
1306
|
+
var err = new PyErr("RecursionError", "maximum recursion depth exceeded");
|
|
1307
|
+
if (first >= 0) { var w = snapshot(); w.Add(new Where(file, first)); err.where = w; }
|
|
1308
|
+
throw err;
|
|
1309
|
+
}
|
|
1310
|
+
var f = new Frame(file, line); frames.Add(f); return f;
|
|
1311
|
+
}
|
|
1312
|
+
public static void leave() { frames.RemoveAt(frames.Count - 1); }
|
|
1313
|
+
public static Frame topFrame() => frames[frames.Count - 1];
|
|
1314
|
+
public static Exception fail(Exception e) { var err = asPyErr(e); if (err.where == null) err.where = snapshot(); return err; }
|
|
1315
|
+
static object withFrame(Frame frame, Func<object> fn)
|
|
1316
|
+
{
|
|
1317
|
+
if (frames.Count >= MAX_FRAMES) throw new PyErr("RecursionError", "maximum recursion depth exceeded");
|
|
1318
|
+
frames.Add(frame);
|
|
1319
|
+
try { return fn(); } catch (Exception e) { throw fail(e); } finally { frames.RemoveAt(frames.Count - 1); }
|
|
1320
|
+
}
|
|
1321
|
+
public static Func<object, object> keyAt(Frame F, Func<object, object> get)
|
|
1322
|
+
{
|
|
1323
|
+
var frame = new Frame(F.file, F.line);
|
|
1324
|
+
return item => withFrame(frame, () => get(item));
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
public static void say(string text) { stdout.Write(text); stdout.Write('\n'); }
|
|
1328
|
+
static void report(Exception e) { stderr.Write(describeError(asPyErr(e))); stderr.Write('\n'); exitCode = 1; aborted = true; }
|
|
1329
|
+
|
|
1330
|
+
/** Work out a file's kept values; an error stops the program with a Thunder message. */
|
|
1331
|
+
public static void init(string file, Action<Frame> fn)
|
|
1332
|
+
{
|
|
1333
|
+
if (aborted) return;
|
|
1334
|
+
var F = new Frame(file, 0);
|
|
1335
|
+
try { withFrame(F, () => { fn(F); return null; }); } catch (Exception e) { report(e); }
|
|
1336
|
+
}
|
|
1337
|
+
public static void run(Action main) { if (aborted) return; try { main(); } catch (Exception e) { report(e); } }
|
|
1338
|
+
public static void runTests((string file, (string title, Action fn, int line)[] tests)[] modules)
|
|
1339
|
+
{
|
|
1340
|
+
if (aborted) return;
|
|
1341
|
+
int passed = 0, failed = 0;
|
|
1342
|
+
foreach (var (file, tests) in modules)
|
|
1343
|
+
foreach (var (title, fn, line) in tests)
|
|
1344
|
+
{
|
|
1345
|
+
try { fn(); passed++; say("PASS " + title + " (" + file + ", line " + line + ")"); }
|
|
1346
|
+
catch (Exception e) { failed++; say("FAIL " + title + " (" + file + ", line " + line + ")"); say(" " + describeError(asPyErr(e))); }
|
|
1347
|
+
}
|
|
1348
|
+
int total = passed + failed;
|
|
1349
|
+
say(total + " test" + (total == 1 ? "" : "s") + ": " + passed + " passed, " + failed + " failed");
|
|
1350
|
+
if (failed > 0) exitCode = 1;
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
/** Run a program on a thread with a deep stack (as deep as Python lets calls nest), then exit with its status. */
|
|
1354
|
+
public static int Start(Action body)
|
|
1355
|
+
{
|
|
1356
|
+
stdout = new StreamWriter(Console.OpenStandardOutput(), new UTF8Encoding(false)) { AutoFlush = false };
|
|
1357
|
+
stderr = new StreamWriter(Console.OpenStandardError(), new UTF8Encoding(false)) { AutoFlush = false };
|
|
1358
|
+
frames.Clear(); aborted = false; exitCode = 0;
|
|
1359
|
+
Exception crash = null;
|
|
1360
|
+
var th = new Thread(() => { try { body(); } catch (Exception e) { crash = e; } }, 1024 * 1024 * 1024);
|
|
1361
|
+
th.Start(); th.Join();
|
|
1362
|
+
stdout.Flush(); stderr.Flush();
|
|
1363
|
+
if (crash != null) { Console.Error.WriteLine("The compiled program failed: " + crash); return 70; }
|
|
1364
|
+
return exitCode;
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
}
|