@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.
- package/CHANGELOG.md +212 -0
- package/README.md +4 -1
- package/dist/core.cjs +2080 -278
- package/dist/index.cjs +12742 -10943
- package/dist/learn.cjs +12976 -3598
- package/package.json +2 -2
- package/src/cli-home.mjs +242 -0
- package/src/cli.mjs +135 -41
- package/src/core/ThunderRuntime.cs +1367 -0
- package/src/core/check.mjs +158 -2
- package/src/core/cli.mjs +208 -17
- package/src/core/csharp-run.mjs +184 -0
- package/src/core/diagnostics.mjs +13 -0
- package/src/core/engine-core.mjs +855 -0
- package/src/core/engine-values.mjs +1054 -0
- package/src/core/engine-worker.mjs +15 -0
- package/src/core/engine.mjs +63 -0
- package/src/core/format.mjs +191 -3
- package/src/core/go-run.mjs +106 -0
- package/src/core/index.mjs +3 -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 +43 -8
- 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/runtime-typescript.mjs +119 -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-python.mjs +2 -1
- package/src/core/target-react.mjs +270 -0
- package/src/core/target-rust.mjs +534 -0
- package/src/core/target-typescript.mjs +466 -0
- package/src/core/typescript-run.mjs +114 -0
- package/src/core.d.ts +18 -0
- package/src/core.mjs +1 -0
- package/src/emit.mjs +1 -1
- package/src/faithful.mjs +30 -0
- package/src/learn-lessons.mjs +245 -1
- package/src/learn.d.mts +8 -0
- package/src/learn.mjs +40 -4
- package/src/libraries.mjs +10 -3
- package/src/model.mjs +50 -8
- package/src/read-level.mjs +192 -0
- package/src/read-repo-fs.mjs +3 -1
- package/src/read.mjs +28 -5
- package/src/replay-cli.mjs +123 -0
- package/src/say-less.mjs +152 -11
- package/src/screens.mjs +833 -0
- package/src/steps.mjs +430 -19
- package/src/term.mjs +132 -0
- package/src/try-cli.mjs +225 -0
- package/src/why-cli.mjs +17 -7
- package/src/why.d.mts +17 -7
- package/src/why.mjs +114 -33
|
@@ -0,0 +1,1645 @@
|
|
|
1
|
+
// thunder_runtime.rs: written by the Thunder compiler next to compiled Rust. Standard library only, no crates.
|
|
2
|
+
//
|
|
3
|
+
// One meaning of Thunder: every value and rule here is a line-by-line port of the Thunder engine's own value code
|
|
4
|
+
// (compiler/src/core/engine-values.mjs), which itself follows the Python target. The same program prints the same
|
|
5
|
+
// output, and fails with the same words, on Python, the Thunder engine, compiled TypeScript, and compiled Rust
|
|
6
|
+
// (compiler/test/core-engines.mjs checks every Core test program on all of them).
|
|
7
|
+
//
|
|
8
|
+
// Values: whole number -> Int (arbitrary size) decimal number -> Dec (exact, like Python's Decimal)
|
|
9
|
+
// money -> Money text -> Text yes/no -> Bool nothing -> Nothing
|
|
10
|
+
// list -> List (shared, like Python's) a pair from a map -> Tuple map -> Map record -> Record
|
|
11
|
+
//
|
|
12
|
+
// An error is a Rust panic carrying a TErr: it unwinds to the nearest frame, which remembers the Thunder line it
|
|
13
|
+
// happened on, exactly as the other targets' exceptions do.
|
|
14
|
+
#![allow(dead_code, clippy::all, non_snake_case, unused_variables, unused_mut)]
|
|
15
|
+
|
|
16
|
+
use std::cell::RefCell;
|
|
17
|
+
use std::cmp::Ordering;
|
|
18
|
+
use std::collections::HashMap;
|
|
19
|
+
use std::fmt::Write as _;
|
|
20
|
+
use std::io::Write as _;
|
|
21
|
+
use std::rc::Rc;
|
|
22
|
+
|
|
23
|
+
// ── Whole numbers of any size ───────────────────────────────────────────────────────────────────────────────────
|
|
24
|
+
|
|
25
|
+
const BASE: u64 = 1_000_000_000;
|
|
26
|
+
|
|
27
|
+
/// A whole number of any size: sign and magnitude (base 10^9, least significant limb first).
|
|
28
|
+
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
29
|
+
pub struct BigInt { neg: bool, mag: Vec<u32> }
|
|
30
|
+
|
|
31
|
+
fn trim(m: &mut Vec<u32>) { while m.len() > 1 && *m.last().unwrap() == 0 { m.pop(); } if m.is_empty() { m.push(0); } }
|
|
32
|
+
fn mag_is_zero(m: &[u32]) -> bool { m.len() == 1 && m[0] == 0 }
|
|
33
|
+
fn mag_cmp(a: &[u32], b: &[u32]) -> Ordering {
|
|
34
|
+
if a.len() != b.len() { return a.len().cmp(&b.len()); }
|
|
35
|
+
for i in (0..a.len()).rev() { if a[i] != b[i] { return a[i].cmp(&b[i]); } }
|
|
36
|
+
Ordering::Equal
|
|
37
|
+
}
|
|
38
|
+
fn mag_add(a: &[u32], b: &[u32]) -> Vec<u32> {
|
|
39
|
+
let mut out = Vec::with_capacity(a.len().max(b.len()) + 1);
|
|
40
|
+
let mut carry = 0u64;
|
|
41
|
+
for i in 0..a.len().max(b.len()) {
|
|
42
|
+
let s = *a.get(i).unwrap_or(&0) as u64 + *b.get(i).unwrap_or(&0) as u64 + carry;
|
|
43
|
+
out.push((s % BASE) as u32);
|
|
44
|
+
carry = s / BASE;
|
|
45
|
+
}
|
|
46
|
+
if carry > 0 { out.push(carry as u32); }
|
|
47
|
+
trim(&mut out);
|
|
48
|
+
out
|
|
49
|
+
}
|
|
50
|
+
/// a - b, where a >= b.
|
|
51
|
+
fn mag_sub(a: &[u32], b: &[u32]) -> Vec<u32> {
|
|
52
|
+
let mut out = Vec::with_capacity(a.len());
|
|
53
|
+
let mut borrow = 0i64;
|
|
54
|
+
for i in 0..a.len() {
|
|
55
|
+
let mut d = a[i] as i64 - *b.get(i).unwrap_or(&0) as i64 - borrow;
|
|
56
|
+
if d < 0 { d += BASE as i64; borrow = 1; } else { borrow = 0; }
|
|
57
|
+
out.push(d as u32);
|
|
58
|
+
}
|
|
59
|
+
trim(&mut out);
|
|
60
|
+
out
|
|
61
|
+
}
|
|
62
|
+
fn mag_mul(a: &[u32], b: &[u32]) -> Vec<u32> {
|
|
63
|
+
if mag_is_zero(a) || mag_is_zero(b) { return vec![0]; }
|
|
64
|
+
let mut acc = vec![0u64; a.len() + b.len() + 1];
|
|
65
|
+
for (i, &x) in a.iter().enumerate() {
|
|
66
|
+
let mut carry = 0u64;
|
|
67
|
+
for (j, &y) in b.iter().enumerate() {
|
|
68
|
+
let t = acc[i + j] + x as u64 * y as u64 + carry;
|
|
69
|
+
acc[i + j] = t % BASE;
|
|
70
|
+
carry = t / BASE;
|
|
71
|
+
}
|
|
72
|
+
let mut k = i + b.len();
|
|
73
|
+
while carry > 0 { let t = acc[k] + carry; acc[k] = t % BASE; carry = t / BASE; k += 1; }
|
|
74
|
+
}
|
|
75
|
+
let mut out: Vec<u32> = acc.into_iter().map(|x| x as u32).collect();
|
|
76
|
+
trim(&mut out);
|
|
77
|
+
out
|
|
78
|
+
}
|
|
79
|
+
fn mag_mul_small(a: &[u32], m: u32) -> Vec<u32> {
|
|
80
|
+
let mut out = Vec::with_capacity(a.len() + 1);
|
|
81
|
+
let mut carry = 0u64;
|
|
82
|
+
for &x in a { let t = x as u64 * m as u64 + carry; out.push((t % BASE) as u32); carry = t / BASE; }
|
|
83
|
+
if carry > 0 { out.push(carry as u32); }
|
|
84
|
+
trim(&mut out);
|
|
85
|
+
out
|
|
86
|
+
}
|
|
87
|
+
/// (quotient, remainder) of magnitudes; b is not zero.
|
|
88
|
+
fn mag_divmod(a: &[u32], b: &[u32]) -> (Vec<u32>, Vec<u32>) {
|
|
89
|
+
if mag_cmp(a, b) == Ordering::Less { return (vec![0], a.to_vec()); }
|
|
90
|
+
if b.len() == 1 {
|
|
91
|
+
let d = b[0] as u64;
|
|
92
|
+
let mut q = vec![0u32; a.len()];
|
|
93
|
+
let mut r = 0u64;
|
|
94
|
+
for i in (0..a.len()).rev() { let cur = r * BASE + a[i] as u64; q[i] = (cur / d) as u32; r = cur % d; }
|
|
95
|
+
trim(&mut q);
|
|
96
|
+
return (q, vec![r as u32]);
|
|
97
|
+
}
|
|
98
|
+
let mut q = vec![0u32; a.len()];
|
|
99
|
+
let mut r: Vec<u32> = vec![0];
|
|
100
|
+
for i in (0..a.len()).rev() {
|
|
101
|
+
// r = r * BASE + a[i]
|
|
102
|
+
let mut nr = Vec::with_capacity(r.len() + 1);
|
|
103
|
+
nr.push(a[i]);
|
|
104
|
+
nr.extend_from_slice(&r);
|
|
105
|
+
trim(&mut nr);
|
|
106
|
+
r = nr;
|
|
107
|
+
if mag_cmp(&r, b) == Ordering::Less { continue; }
|
|
108
|
+
// The quotient digit, by binary search between estimates.
|
|
109
|
+
let (mut lo, mut hi) = (0u64, BASE - 1);
|
|
110
|
+
while lo < hi {
|
|
111
|
+
let mid = (lo + hi + 1) / 2;
|
|
112
|
+
if mag_cmp(&mag_mul_small(b, mid as u32), &r) != Ordering::Greater { lo = mid; } else { hi = mid - 1; }
|
|
113
|
+
}
|
|
114
|
+
q[i] = lo as u32;
|
|
115
|
+
r = mag_sub(&r, &mag_mul_small(b, lo as u32));
|
|
116
|
+
}
|
|
117
|
+
trim(&mut q);
|
|
118
|
+
(q, r)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
impl BigInt {
|
|
122
|
+
pub fn zero() -> BigInt { BigInt { neg: false, mag: vec![0] } }
|
|
123
|
+
pub fn from_i64(n: i64) -> BigInt {
|
|
124
|
+
let neg = n < 0;
|
|
125
|
+
let mut u = n.unsigned_abs();
|
|
126
|
+
let mut mag = Vec::new();
|
|
127
|
+
if u == 0 { mag.push(0); }
|
|
128
|
+
while u > 0 { mag.push((u % BASE) as u32); u /= BASE; }
|
|
129
|
+
BigInt { neg, mag }
|
|
130
|
+
}
|
|
131
|
+
fn norm(mut self) -> BigInt { trim(&mut self.mag); if mag_is_zero(&self.mag) { self.neg = false; } self }
|
|
132
|
+
pub fn parse(text: &str) -> Option<BigInt> {
|
|
133
|
+
let t = text.trim().replace('_', "");
|
|
134
|
+
let (neg, digits) = if let Some(r) = t.strip_prefix('-') { (true, r.to_string()) } else if let Some(r) = t.strip_prefix('+') { (false, r.to_string()) } else { (false, t.clone()) };
|
|
135
|
+
if digits.is_empty() || !digits.bytes().all(|c| c.is_ascii_digit()) { return None; }
|
|
136
|
+
let bytes = digits.as_bytes();
|
|
137
|
+
let mut mag = Vec::new();
|
|
138
|
+
let mut end = bytes.len();
|
|
139
|
+
while end > 0 {
|
|
140
|
+
let start = end.saturating_sub(9);
|
|
141
|
+
mag.push(std::str::from_utf8(&bytes[start..end]).unwrap().parse::<u32>().unwrap());
|
|
142
|
+
end = start;
|
|
143
|
+
}
|
|
144
|
+
Some(BigInt { neg, mag }.norm())
|
|
145
|
+
}
|
|
146
|
+
pub fn is_zero(&self) -> bool { mag_is_zero(&self.mag) }
|
|
147
|
+
pub fn is_neg(&self) -> bool { self.neg }
|
|
148
|
+
pub fn abs(&self) -> BigInt { BigInt { neg: false, mag: self.mag.clone() } }
|
|
149
|
+
pub fn negate(&self) -> BigInt { BigInt { neg: !self.neg, mag: self.mag.clone() }.norm() }
|
|
150
|
+
pub fn add(&self, o: &BigInt) -> BigInt {
|
|
151
|
+
if self.neg == o.neg { return BigInt { neg: self.neg, mag: mag_add(&self.mag, &o.mag) }.norm(); }
|
|
152
|
+
match mag_cmp(&self.mag, &o.mag) {
|
|
153
|
+
Ordering::Equal => BigInt::zero(),
|
|
154
|
+
Ordering::Greater => BigInt { neg: self.neg, mag: mag_sub(&self.mag, &o.mag) }.norm(),
|
|
155
|
+
Ordering::Less => BigInt { neg: o.neg, mag: mag_sub(&o.mag, &self.mag) }.norm(),
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
pub fn sub(&self, o: &BigInt) -> BigInt { self.add(&o.negate()) }
|
|
159
|
+
pub fn mul(&self, o: &BigInt) -> BigInt { BigInt { neg: self.neg != o.neg, mag: mag_mul(&self.mag, &o.mag) }.norm() }
|
|
160
|
+
pub fn mul_small(&self, m: u32) -> BigInt { BigInt { neg: self.neg, mag: mag_mul_small(&self.mag, m) }.norm() }
|
|
161
|
+
/// Truncated division (toward zero), as JavaScript's BigInt / and %.
|
|
162
|
+
pub fn divrem(&self, o: &BigInt) -> (BigInt, BigInt) {
|
|
163
|
+
let (q, r) = mag_divmod(&self.mag, &o.mag);
|
|
164
|
+
(BigInt { neg: self.neg != o.neg, mag: q }.norm(), BigInt { neg: self.neg, mag: r }.norm())
|
|
165
|
+
}
|
|
166
|
+
pub fn cmp(&self, o: &BigInt) -> Ordering {
|
|
167
|
+
match (self.neg, o.neg) {
|
|
168
|
+
(false, true) => Ordering::Greater,
|
|
169
|
+
(true, false) => Ordering::Less,
|
|
170
|
+
(false, false) => mag_cmp(&self.mag, &o.mag),
|
|
171
|
+
(true, true) => mag_cmp(&o.mag, &self.mag),
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
pub fn pow10(n: i64) -> BigInt {
|
|
175
|
+
let mut mag = vec![0u32; (n / 9) as usize];
|
|
176
|
+
mag.push(10u32.pow((n % 9) as u32));
|
|
177
|
+
BigInt { neg: false, mag }
|
|
178
|
+
}
|
|
179
|
+
pub fn is_even(&self) -> bool { self.mag[0] % 2 == 0 }
|
|
180
|
+
pub fn to_i64(&self) -> Option<i64> {
|
|
181
|
+
if self.mag.len() > 3 { return None; }
|
|
182
|
+
let mut v: i128 = 0;
|
|
183
|
+
for &l in self.mag.iter().rev() { v = v * BASE as i128 + l as i128; }
|
|
184
|
+
if self.neg { v = -v; }
|
|
185
|
+
if v > i64::MAX as i128 || v < i64::MIN as i128 { None } else { Some(v as i64) }
|
|
186
|
+
}
|
|
187
|
+
pub fn ndigits(&self) -> i64 {
|
|
188
|
+
let top = *self.mag.last().unwrap();
|
|
189
|
+
(self.mag.len() as i64 - 1) * 9 + if top == 0 { 1 } else { top.to_string().len() as i64 }
|
|
190
|
+
}
|
|
191
|
+
pub fn digits(&self) -> String {
|
|
192
|
+
let mut s = String::new();
|
|
193
|
+
let mut first = true;
|
|
194
|
+
for &l in self.mag.iter().rev() { if first { let _ = write!(s, "{}", l); first = false; } else { let _ = write!(s, "{:09}", l); } }
|
|
195
|
+
s
|
|
196
|
+
}
|
|
197
|
+
pub fn to_string(&self) -> String { format!("{}{}", if self.neg { "-" } else { "" }, self.digits()) }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
fn big(n: i64) -> BigInt { BigInt::from_i64(n) }
|
|
201
|
+
|
|
202
|
+
// ── Exact decimals: Python's Decimal with its default context (28 digits, half-even when a result is too long) ──
|
|
203
|
+
|
|
204
|
+
const PREC: i64 = 28;
|
|
205
|
+
|
|
206
|
+
/// sign (true when negative), coefficient >= 0, exponent.
|
|
207
|
+
#[derive(Clone, Debug)]
|
|
208
|
+
pub struct Dec { pub s: bool, pub c: BigInt, pub e: i64 }
|
|
209
|
+
|
|
210
|
+
fn p10(n: i64) -> BigInt { BigInt::pow10(n) }
|
|
211
|
+
|
|
212
|
+
impl Dec {
|
|
213
|
+
pub fn new(s: bool, c: BigInt, e: i64) -> Dec { Dec { s, c, e } }
|
|
214
|
+
pub fn int(n: &BigInt) -> Dec { Dec { s: n.is_neg(), c: n.abs(), e: 0 } }
|
|
215
|
+
/// Decimal("text"): exact; None when the text is not a number.
|
|
216
|
+
pub fn parse(text: &str) -> Option<Dec> {
|
|
217
|
+
let t: String = text.trim().replace('_', "");
|
|
218
|
+
let b = t.as_bytes();
|
|
219
|
+
let mut i = 0;
|
|
220
|
+
let mut neg = false;
|
|
221
|
+
if i < b.len() && (b[i] == b'+' || b[i] == b'-') { neg = b[i] == b'-'; i += 1; }
|
|
222
|
+
let s0 = i;
|
|
223
|
+
while i < b.len() && b[i].is_ascii_digit() { i += 1; }
|
|
224
|
+
let int_part = &t[s0..i];
|
|
225
|
+
let mut frac = "";
|
|
226
|
+
if i < b.len() && b[i] == b'.' { i += 1; let f0 = i; while i < b.len() && b[i].is_ascii_digit() { i += 1; } frac = &t[f0..i]; }
|
|
227
|
+
if int_part.is_empty() && frac.is_empty() { return None; }
|
|
228
|
+
let mut exp: i64 = 0;
|
|
229
|
+
if i < b.len() && (b[i] == b'e' || b[i] == b'E') {
|
|
230
|
+
i += 1;
|
|
231
|
+
let e0 = i;
|
|
232
|
+
if i < b.len() && (b[i] == b'+' || b[i] == b'-') { i += 1; }
|
|
233
|
+
let d0 = i;
|
|
234
|
+
while i < b.len() && b[i].is_ascii_digit() { i += 1; }
|
|
235
|
+
if d0 == i { return None; }
|
|
236
|
+
exp = t[e0..i].parse::<i64>().ok()?;
|
|
237
|
+
}
|
|
238
|
+
if i != b.len() { return None; }
|
|
239
|
+
let digits = format!("{}{}", int_part, frac);
|
|
240
|
+
let c = BigInt::parse(if digits.is_empty() { "0" } else { &digits })?;
|
|
241
|
+
Some(Dec { s: neg, c, e: exp - frac.len() as i64 })
|
|
242
|
+
}
|
|
243
|
+
pub fn is_zero(&self) -> bool { self.c.is_zero() }
|
|
244
|
+
/// _fix: round to 28 significant digits, half to even.
|
|
245
|
+
pub fn fix(self) -> Dec {
|
|
246
|
+
let d = self.c.ndigits() - PREC;
|
|
247
|
+
if d <= 0 { return self; }
|
|
248
|
+
let p = p10(d);
|
|
249
|
+
let (mut q, r) = self.c.divrem(&p);
|
|
250
|
+
let half = p10(d - 1).mul_small(5);
|
|
251
|
+
let c = r.cmp(&half);
|
|
252
|
+
if c == Ordering::Greater || (c == Ordering::Equal && !q.is_even()) { q = q.add(&big(1)); }
|
|
253
|
+
let mut e = self.e + d;
|
|
254
|
+
if q.ndigits() > PREC { q = q.divrem(&big(10)).0; e += 1; }
|
|
255
|
+
Dec { s: self.s, c: q, e }
|
|
256
|
+
}
|
|
257
|
+
pub fn signed(&self) -> BigInt { if self.s { self.c.negate() } else { self.c.clone() } }
|
|
258
|
+
pub fn add(a: &Dec, b: &Dec) -> Dec {
|
|
259
|
+
let e = a.e.min(b.e);
|
|
260
|
+
let x = a.signed().mul(&p10(a.e - e));
|
|
261
|
+
let y = b.signed().mul(&p10(b.e - e));
|
|
262
|
+
let sum = x.add(&y);
|
|
263
|
+
let s = if sum.is_zero() {
|
|
264
|
+
if a.s && b.s && a.c.is_zero() && b.c.is_zero() { true } else if a.c.is_zero() && b.c.is_zero() { a.s && b.s } else { false }
|
|
265
|
+
} else { sum.is_neg() };
|
|
266
|
+
Dec { s, c: sum.abs(), e }.fix()
|
|
267
|
+
}
|
|
268
|
+
pub fn negated(&self) -> Dec { Dec { s: !self.s, c: self.c.clone(), e: self.e } }
|
|
269
|
+
pub fn sub(a: &Dec, b: &Dec) -> Dec { Dec::add(a, &b.negated()) }
|
|
270
|
+
pub fn mul(a: &Dec, b: &Dec) -> Dec { Dec { s: a.s != b.s, c: a.c.mul(&b.c), e: a.e + b.e }.fix() }
|
|
271
|
+
/// Python's Decimal division: exact when it can be, else 28 digits.
|
|
272
|
+
pub fn div(a: &Dec, b: &Dec) -> Dec {
|
|
273
|
+
let s = a.s != b.s;
|
|
274
|
+
if a.c.is_zero() { return Dec { s, c: BigInt::zero(), e: a.e - b.e }.fix(); }
|
|
275
|
+
let shift = b.c.ndigits() - a.c.ndigits() + PREC + 1;
|
|
276
|
+
let mut exp = a.e - b.e - shift;
|
|
277
|
+
let (mut coeff, rem);
|
|
278
|
+
if shift >= 0 { let n = a.c.mul(&p10(shift)); let qr = n.divrem(&b.c); coeff = qr.0; rem = qr.1; }
|
|
279
|
+
else { let d = b.c.mul(&p10(-shift)); let qr = a.c.divrem(&d); coeff = qr.0; rem = qr.1; }
|
|
280
|
+
if !rem.is_zero() {
|
|
281
|
+
if coeff.divrem(&big(5)).1.is_zero() { coeff = coeff.add(&big(1)); }
|
|
282
|
+
} else {
|
|
283
|
+
let ideal = a.e - b.e;
|
|
284
|
+
while exp < ideal && coeff.divrem(&big(10)).1.is_zero() { coeff = coeff.divrem(&big(10)).0; exp += 1; }
|
|
285
|
+
}
|
|
286
|
+
Dec { s, c: coeff, e: exp }.fix()
|
|
287
|
+
}
|
|
288
|
+
/// Decimal % Decimal: the remainder with the sign of the dividend.
|
|
289
|
+
pub fn rem(a: &Dec, b: &Dec) -> Dec {
|
|
290
|
+
let e = a.e.min(b.e);
|
|
291
|
+
let x = a.c.mul(&p10(a.e - e));
|
|
292
|
+
let y = b.c.mul(&p10(b.e - e));
|
|
293
|
+
Dec { s: a.s, c: x.divrem(&y).1, e }.fix()
|
|
294
|
+
}
|
|
295
|
+
pub fn neg(&self) -> Dec { (if self.c.is_zero() { Dec { s: false, c: BigInt::zero(), e: self.e } } else { self.negated() }).fix() }
|
|
296
|
+
pub fn abs(&self) -> Dec { Dec { s: false, c: self.c.clone(), e: self.e }.fix() }
|
|
297
|
+
pub fn cmp(a: &Dec, b: &Dec) -> Ordering {
|
|
298
|
+
let e = a.e.min(b.e);
|
|
299
|
+
let x = a.signed().mul(&p10(a.e - e));
|
|
300
|
+
let y = b.signed().mul(&p10(b.e - e));
|
|
301
|
+
x.cmp(&y)
|
|
302
|
+
}
|
|
303
|
+
/// quantize to exponent `e`, rounding half away from zero.
|
|
304
|
+
pub fn quantize_half_up(&self, e: i64) -> Dec {
|
|
305
|
+
if e <= self.e { return Dec { s: self.s, c: self.c.mul(&p10(self.e - e)), e }; }
|
|
306
|
+
let p = p10(e - self.e);
|
|
307
|
+
let (mut q, r) = self.c.divrem(&p);
|
|
308
|
+
if r.mul_small(2).cmp(&p) != Ordering::Less { q = q.add(&big(1)); }
|
|
309
|
+
Dec { s: self.s, c: q, e }
|
|
310
|
+
}
|
|
311
|
+
pub fn is_integral(&self) -> bool { if self.e >= 0 { return true; } self.c.divrem(&p10(-self.e)).1.is_zero() }
|
|
312
|
+
/// int(d): toward zero.
|
|
313
|
+
pub fn to_bigint(&self) -> BigInt {
|
|
314
|
+
let v = if self.e >= 0 { self.c.mul(&p10(self.e)) } else { self.c.divrem(&p10(-self.e)).0 };
|
|
315
|
+
if self.s { v.negate() } else { v }
|
|
316
|
+
}
|
|
317
|
+
/// str(Decimal): Python's to-scientific-string.
|
|
318
|
+
pub fn to_sci(&self) -> String {
|
|
319
|
+
let digits = self.c.digits();
|
|
320
|
+
let n = digits.len() as i64;
|
|
321
|
+
let left = self.e + n;
|
|
322
|
+
let dot = if self.e <= 0 && left > -6 { left } else { 1 };
|
|
323
|
+
let (ip, fp) = if dot <= 0 { ("0".to_string(), format!(".{}{}", "0".repeat((-dot) as usize), digits)) }
|
|
324
|
+
else if dot >= n { (format!("{}{}", digits, "0".repeat((dot - n) as usize)), String::new()) }
|
|
325
|
+
else { (digits[..dot as usize].to_string(), format!(".{}", &digits[dot as usize..])) };
|
|
326
|
+
let ex = if left == dot { String::new() } else { format!("E{}{}", if left - dot >= 0 { "+" } else { "" }, left - dot) };
|
|
327
|
+
format!("{}{}{}{}", if self.s { "-" } else { "" }, ip, fp, ex)
|
|
328
|
+
}
|
|
329
|
+
/// format(d, "f") or format(d, ",.Nf").
|
|
330
|
+
pub fn to_fixed(&self, places: Option<i64>, group: bool) -> String {
|
|
331
|
+
let d = match places { Some(p) => self.round_half_even(-p), None => self.clone() };
|
|
332
|
+
let digits = d.c.digits();
|
|
333
|
+
let n = digits.len() as i64;
|
|
334
|
+
let dot = d.e + n;
|
|
335
|
+
let (mut ip, fp) = if dot < 0 { ("0".to_string(), format!("{}{}", "0".repeat((-dot) as usize), digits)) }
|
|
336
|
+
else if dot > n { (format!("{}{}", digits, "0".repeat((dot - n) as usize)), String::new()) }
|
|
337
|
+
else { (if dot == 0 { "0".to_string() } else { digits[..dot as usize].to_string() }, digits[dot as usize..].to_string()) };
|
|
338
|
+
if group {
|
|
339
|
+
let b: Vec<char> = ip.chars().collect();
|
|
340
|
+
let mut g = String::new();
|
|
341
|
+
for (i, ch) in b.iter().enumerate() { if i > 0 && (b.len() - i) % 3 == 0 { g.push(','); } g.push(*ch); }
|
|
342
|
+
ip = g;
|
|
343
|
+
}
|
|
344
|
+
format!("{}{}{}", if d.s { "-" } else { "" }, ip, if fp.is_empty() { String::new() } else { format!(".{}", fp) })
|
|
345
|
+
}
|
|
346
|
+
pub fn round_half_even(&self, e: i64) -> Dec {
|
|
347
|
+
if e <= self.e { return Dec { s: self.s, c: self.c.mul(&p10(self.e - e)), e }; }
|
|
348
|
+
let p = p10(e - self.e);
|
|
349
|
+
let (mut q, r) = self.c.divrem(&p);
|
|
350
|
+
let c = r.mul_small(2).cmp(&p);
|
|
351
|
+
if c == Ordering::Greater || (c == Ordering::Equal && !q.is_even()) { q = q.add(&big(1)); }
|
|
352
|
+
Dec { s: self.s, c: q, e }
|
|
353
|
+
}
|
|
354
|
+
/// A key equal for equal numbers (1 and 1.0 and 1.00 are the same map key, as in Python).
|
|
355
|
+
pub fn key(&self) -> String {
|
|
356
|
+
if self.c.is_zero() { return "0".to_string(); }
|
|
357
|
+
let mut c = self.c.clone();
|
|
358
|
+
let mut e = self.e;
|
|
359
|
+
loop { let (q, r) = c.divrem(&big(10)); if !r.is_zero() { break; } c = q; e += 1; }
|
|
360
|
+
format!("{}{}e{}", if self.s { "-" } else { "" }, c.digits(), e)
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// ── Errors ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
365
|
+
|
|
366
|
+
/// An error: a Thunder one (code TC5xx and its words) or one Python itself would raise (its type and message).
|
|
367
|
+
#[derive(Clone, Debug)]
|
|
368
|
+
pub struct TErr {
|
|
369
|
+
pub code: Option<&'static str>,
|
|
370
|
+
pub py_type: String,
|
|
371
|
+
pub message: String,
|
|
372
|
+
/// What a KeyError names, as Thunder shows it.
|
|
373
|
+
pub arg: Option<String>,
|
|
374
|
+
/// Where it happened: the frames' files and lines, outermost first.
|
|
375
|
+
pub at: Option<Vec<(String, i64)>>,
|
|
376
|
+
}
|
|
377
|
+
impl TErr {
|
|
378
|
+
pub fn thunder(&self) -> bool { self.code.is_some() }
|
|
379
|
+
}
|
|
380
|
+
pub fn thunder_err(code: &'static str, m: String, py_type: &str) -> TErr { TErr { code: Some(code), py_type: py_type.to_string(), message: m, arg: None, at: None } }
|
|
381
|
+
pub fn py_err(py_type: &str, m: String) -> TErr { TErr { code: None, py_type: py_type.to_string(), message: m, arg: None, at: None } }
|
|
382
|
+
|
|
383
|
+
/// Raise an error: it unwinds to the nearest frame (or "If this fails", or an Expect that wants it).
|
|
384
|
+
pub fn raise(e: TErr) -> ! { std::panic::panic_any(e) }
|
|
385
|
+
pub fn Stop(m: String) -> ! { raise(thunder_err("TC507", m, "Stop")) }
|
|
386
|
+
fn rule_broken(m: String) -> ! { raise(thunder_err("TC504", m, "RuleBroken")) }
|
|
387
|
+
fn expectation_failed(m: String) -> ! { raise(thunder_err("TC505", m, "ExpectationFailed")) }
|
|
388
|
+
fn kind_mismatch(m: String) -> ! { raise(thunder_err("TC506", m, "TypeError")) }
|
|
389
|
+
fn conversion_failed(m: String) -> ! { raise(thunder_err("TC509", m, "ValueError")) }
|
|
390
|
+
fn missing_value(m: String) -> ! { raise(thunder_err("TC503", m, "LookupError")) }
|
|
391
|
+
fn divided_by_zero() -> ! { raise(thunder_err("TC501", "You divided by zero.".to_string(), "ZeroDivisionError")) }
|
|
392
|
+
fn type_err(m: String) -> ! { raise(py_err("TypeError", m)) }
|
|
393
|
+
|
|
394
|
+
/// explain(error) in thunder_runtime.py: the error as a sentence.
|
|
395
|
+
pub fn explain_err(e: &TErr) -> String {
|
|
396
|
+
if e.thunder() { return e.message.clone(); }
|
|
397
|
+
let t = e.py_type.as_str();
|
|
398
|
+
if t == "ZeroDivisionError" || t == "DivisionByZero" { return "You divided by zero.".to_string(); }
|
|
399
|
+
if t == "InvalidOperation" { return "This calculation has no answer (for example, zero divided by zero).".to_string(); }
|
|
400
|
+
if t == "KeyError" { return format!("There is no entry for {}.", e.arg.clone().unwrap_or_else(|| "nothing".to_string())); }
|
|
401
|
+
if (t == "TypeError" || t == "AttributeError") && e.message.contains("NoneType") { return "A value was nothing where a value was needed.".to_string(); }
|
|
402
|
+
if t == "TypeError" { return format!("Values of different kinds were mixed ({}).", e.message); }
|
|
403
|
+
if t == "RecursionError" { return "A function called itself too many times.".to_string(); }
|
|
404
|
+
format!("{}: {}", t, e.message)
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/// _code(error) in thunder_runtime.py.
|
|
408
|
+
pub fn code_of(e: &TErr) -> &'static str {
|
|
409
|
+
if let Some(c) = e.code { return c; }
|
|
410
|
+
let t = e.py_type.as_str();
|
|
411
|
+
if t == "ZeroDivisionError" || t == "DivisionByZero" { return "TC501"; }
|
|
412
|
+
if (t == "TypeError" || t == "AttributeError") && e.message.contains("NoneType") { return "TC502"; }
|
|
413
|
+
if t == "KeyError" { return "TC503"; }
|
|
414
|
+
if t == "TypeError" { return "TC506"; }
|
|
415
|
+
"TC508"
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/// describe_error(error): "main.thunder, line 3 (reached from line 7): … [TC501]".
|
|
419
|
+
pub fn describe_error(e: &TErr) -> String {
|
|
420
|
+
let at = e.at.clone().unwrap_or_default();
|
|
421
|
+
let mut message = explain_err(e);
|
|
422
|
+
let code = code_of(e);
|
|
423
|
+
if code == "TC508" && !e.thunder() { message = format!("Python code used by this line failed: {}", message); }
|
|
424
|
+
let mut place = match at.last() { Some((f, l)) => format!("{}, line {}", f, l), None => "In the program".to_string() };
|
|
425
|
+
if at.len() > 1 {
|
|
426
|
+
let callers: Vec<String> = at[..at.len() - 1].iter().rev().map(|(_, l)| l.to_string()).collect();
|
|
427
|
+
place = format!("{} (reached from line {})", place, callers.join(", then line "));
|
|
428
|
+
}
|
|
429
|
+
format!("{}: {} [{}]", place, message, code)
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// ── Values ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
433
|
+
|
|
434
|
+
/// A record's kind: its name, its fields (name and Thunder kind), and the Never rules on each field.
|
|
435
|
+
pub struct Kind { pub py: &'static str, pub fields: Vec<(&'static str, &'static str)>, pub rules: Vec<(&'static str, Vec<Rule>)> }
|
|
436
|
+
/// A Never rule: broken when `cond` is true of the new value.
|
|
437
|
+
pub struct Rule { pub cond: fn(Value) -> Value, pub text: &'static str, pub line: i64 }
|
|
438
|
+
|
|
439
|
+
/// A record: its kind, and its field values (in declaration order).
|
|
440
|
+
pub struct Rec { pub kind: Rc<Kind>, pub f: Vec<(&'static str, Value)> }
|
|
441
|
+
impl Rec {
|
|
442
|
+
fn get(&self, name: &str) -> Option<Value> { self.f.iter().find(|(k, _)| *k == name).map(|(_, v)| v.clone()) }
|
|
443
|
+
fn has(&self, name: &str) -> bool { self.f.iter().any(|(k, _)| *k == name) }
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/// A Python dict: insertion order kept; keys equal the way Python compares them (1 == 1.0 == True).
|
|
447
|
+
#[derive(Clone, Default)]
|
|
448
|
+
pub struct PyDict { entries: Vec<Option<(Value, Value)>>, index: HashMap<String, usize>, live: usize }
|
|
449
|
+
impl PyDict {
|
|
450
|
+
pub fn new() -> PyDict { PyDict::default() }
|
|
451
|
+
pub fn has(&self, k: &Value) -> bool { self.index.contains_key(&key_of(k)) }
|
|
452
|
+
pub fn get(&self, k: &Value) -> Option<Value> { self.index.get(&key_of(k)).and_then(|&i| self.entries[i].as_ref().map(|(_, v)| v.clone())) }
|
|
453
|
+
pub fn set(&mut self, k: Value, v: Value) {
|
|
454
|
+
let id = key_of(&k);
|
|
455
|
+
if let Some(&i) = self.index.get(&id) { if let Some(e) = self.entries[i].as_mut() { e.1 = v; } return; }
|
|
456
|
+
self.index.insert(id, self.entries.len());
|
|
457
|
+
self.entries.push(Some((k, v)));
|
|
458
|
+
self.live += 1;
|
|
459
|
+
}
|
|
460
|
+
pub fn delete(&mut self, k: &Value) { if let Some(i) = self.index.remove(&key_of(k)) { self.entries[i] = None; self.live -= 1; } }
|
|
461
|
+
pub fn len(&self) -> usize { self.live }
|
|
462
|
+
pub fn pairs(&self) -> Vec<(Value, Value)> { self.entries.iter().filter_map(|e| e.clone()).collect() }
|
|
463
|
+
pub fn keys(&self) -> Vec<Value> { self.pairs().into_iter().map(|(k, _)| k).collect() }
|
|
464
|
+
pub fn values(&self) -> Vec<Value> { self.pairs().into_iter().map(|(_, v)| v).collect() }
|
|
465
|
+
fn key_ids(&self) -> Vec<String> { self.pairs().iter().map(|(k, _)| key_of(k)).collect() }
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
#[derive(Clone)]
|
|
469
|
+
pub enum Value {
|
|
470
|
+
Nothing,
|
|
471
|
+
Bool(bool),
|
|
472
|
+
Int(BigInt),
|
|
473
|
+
Dec(Dec),
|
|
474
|
+
Money(Dec),
|
|
475
|
+
Text(Rc<String>),
|
|
476
|
+
List(Rc<RefCell<Vec<Value>>>),
|
|
477
|
+
Tuple(Rc<Vec<Value>>),
|
|
478
|
+
Map(Rc<RefCell<PyDict>>),
|
|
479
|
+
Record(Rc<RefCell<Rec>>),
|
|
480
|
+
Date(i64, i64, i64),
|
|
481
|
+
NotGiven,
|
|
482
|
+
}
|
|
483
|
+
use Value::*;
|
|
484
|
+
|
|
485
|
+
pub const NOT_GIVEN: Value = Value::NotGiven;
|
|
486
|
+
pub const NOTHING: Value = Value::Nothing;
|
|
487
|
+
|
|
488
|
+
/// Values the generated code writes literally.
|
|
489
|
+
pub fn int(text: &str) -> Value { Int(BigInt::parse(text).expect("a whole number literal")) }
|
|
490
|
+
pub fn int_n(n: i64) -> Value { Int(big(n)) }
|
|
491
|
+
pub fn dec(text: &str) -> Value { Dec(Dec::parse(text).expect("a decimal literal")) }
|
|
492
|
+
pub fn money(text: &str) -> Value { money_of(&text_v(text)) }
|
|
493
|
+
pub fn text(s: &str) -> Value { Text(Rc::new(s.to_string())) }
|
|
494
|
+
pub fn text_v(s: &str) -> Value { Text(Rc::new(s.to_string())) }
|
|
495
|
+
pub fn string(s: String) -> Value { Text(Rc::new(s)) }
|
|
496
|
+
pub fn yes(b: bool) -> Value { Bool(b) }
|
|
497
|
+
pub fn list(items: Vec<Value>) -> Value { List(Rc::new(RefCell::new(items))) }
|
|
498
|
+
pub fn new_map() -> Value { Map(Rc::new(RefCell::new(PyDict::new()))) }
|
|
499
|
+
pub fn tuple(items: Vec<Value>) -> Value { Tuple(Rc::new(items)) }
|
|
500
|
+
pub fn date(t: &str) -> Value { match parse_date(t) { Some(d) => d, None => raise(py_err("ValueError", format!("Invalid isoformat string: '{}'", t))) } }
|
|
501
|
+
pub fn today() -> Value {
|
|
502
|
+
let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0);
|
|
503
|
+
let (y, m, d) = civil_from_days(secs.div_euclid(86400) + local_offset_days());
|
|
504
|
+
Date(y, m, d)
|
|
505
|
+
}
|
|
506
|
+
fn local_offset_days() -> i64 { 0 }
|
|
507
|
+
fn civil_from_days(z: i64) -> (i64, i64, i64) {
|
|
508
|
+
let z = z + 719468;
|
|
509
|
+
let era = z.div_euclid(146097);
|
|
510
|
+
let doe = z - era * 146097;
|
|
511
|
+
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
|
|
512
|
+
let y = yoe + era * 400;
|
|
513
|
+
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
|
514
|
+
let mp = (5 * doy + 2) / 153;
|
|
515
|
+
let d = doy - (153 * mp + 2) / 5 + 1;
|
|
516
|
+
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
|
517
|
+
(if m <= 2 { y + 1 } else { y }, m, d)
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/// date.fromisoformat for YYYY-MM-DD (and YYYYMMDD); None when it is not a date.
|
|
521
|
+
fn parse_date(text: &str) -> Option<Value> {
|
|
522
|
+
let t = text.as_bytes();
|
|
523
|
+
let digits = |s: &[u8]| s.iter().all(|c| c.is_ascii_digit());
|
|
524
|
+
let (y, mo, d) = if t.len() == 10 && t[4] == b'-' && t[7] == b'-' && digits(&t[0..4]) && digits(&t[5..7]) && digits(&t[8..10]) { (&text[0..4], &text[5..7], &text[8..10]) }
|
|
525
|
+
else if t.len() == 8 && digits(t) { (&text[0..4], &text[4..6], &text[6..8]) }
|
|
526
|
+
else if t.len() == 9 && digits(&t[0..4]) && ((t[4] == b'-' && digits(&t[5..9])) || (t[6] == b'-' && digits(&t[0..6]) && digits(&t[7..9]))) {
|
|
527
|
+
if t[4] == b'-' { (&text[0..4], &text[5..7], &text[7..9]) } else { (&text[0..4], &text[4..6], &text[7..9]) }
|
|
528
|
+
} else { return None; };
|
|
529
|
+
let (y, mo, d): (i64, i64, i64) = (y.parse().ok()?, mo.parse().ok()?, d.parse().ok()?);
|
|
530
|
+
let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
|
|
531
|
+
let days = [31, if leap { 29 } else { 28 }, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
532
|
+
if y < 1 || mo < 1 || mo > 12 || d < 1 || d > days[(mo - 1) as usize] { return None; }
|
|
533
|
+
Some(Date(y, mo, d))
|
|
534
|
+
}
|
|
535
|
+
fn iso(y: i64, m: i64, d: i64) -> String { format!("{:04}-{:02}-{:02}", y, m, d) }
|
|
536
|
+
|
|
537
|
+
// ── Kinds ──────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
538
|
+
|
|
539
|
+
fn is_int(v: &Value) -> bool { matches!(v, Int(_)) }
|
|
540
|
+
fn is_number(v: &Value) -> bool { matches!(v, Int(_) | Dec(_)) } // _is_number: never yes/no
|
|
541
|
+
fn is_int_like(v: &Value) -> bool { matches!(v, Int(_) | Bool(_)) }
|
|
542
|
+
fn is_num_like(v: &Value) -> bool { matches!(v, Int(_) | Bool(_) | Dec(_)) }
|
|
543
|
+
fn as_big(v: &Value) -> BigInt { match v { Int(n) => n.clone(), Bool(b) => big(if *b { 1 } else { 0 }), _ => BigInt::zero() } }
|
|
544
|
+
fn dec_of(v: &Value) -> Dec { match v { Dec(d) => d.clone(), Int(n) => Dec::int(n), Bool(b) => Dec::int(&big(if *b { 1 } else { 0 })), _ => Dec::int(&BigInt::zero()) } }
|
|
545
|
+
fn num_cmp(a: &Value, b: &Value) -> Ordering { if is_int_like(a) && is_int_like(b) { as_big(a).cmp(&as_big(b)) } else { Dec::cmp(&dec_of(a), &dec_of(b)) } }
|
|
546
|
+
|
|
547
|
+
/// Python's type name, as its error messages print it.
|
|
548
|
+
pub fn type_name(v: &Value) -> String {
|
|
549
|
+
match v {
|
|
550
|
+
Nothing => "NoneType".into(),
|
|
551
|
+
Bool(_) => "bool".into(),
|
|
552
|
+
Int(_) => "int".into(),
|
|
553
|
+
Text(_) => "str".into(),
|
|
554
|
+
Dec(_) => "decimal.Decimal".into(),
|
|
555
|
+
Money(_) => "Money".into(),
|
|
556
|
+
List(_) => "list".into(),
|
|
557
|
+
Tuple(_) => "tuple".into(),
|
|
558
|
+
Map(_) => "dict".into(),
|
|
559
|
+
Date(..) => "datetime.date".into(),
|
|
560
|
+
Record(r) => r.borrow().kind.py.to_string(),
|
|
561
|
+
NotGiven => "_NotGiven".into(),
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
fn short_name(v: &Value) -> String { match v { Dec(_) => "Decimal".into(), Date(..) => "date".into(), _ => type_name(v) } }
|
|
565
|
+
|
|
566
|
+
/// _describe(v) in thunder_runtime.py.
|
|
567
|
+
pub fn describe(v: &Value) -> String {
|
|
568
|
+
match v {
|
|
569
|
+
Nothing => "nothing".into(),
|
|
570
|
+
Bool(_) => "a yes/no value".into(),
|
|
571
|
+
Text(s) => format!("the text \"{}\"", s),
|
|
572
|
+
Int(_) | Dec(_) => format!("the number {}", show_s(v)),
|
|
573
|
+
Money(_) => money_str(v),
|
|
574
|
+
_ => format!("a value ({})", short_name(v)),
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
fn money_str(v: &Value) -> String {
|
|
579
|
+
if let Money(a) = v {
|
|
580
|
+
let places = if a.e < 0 { 2.max(-a.e) } else { 2 };
|
|
581
|
+
format!("{}{}", if a.s && !a.c.is_zero() { "-$" } else { "$" }, a.abs().to_fixed(Some(places), true))
|
|
582
|
+
} else { String::new() }
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/// show(v): a value the way Thunder says it.
|
|
586
|
+
pub fn show_s(v: &Value) -> String {
|
|
587
|
+
match v {
|
|
588
|
+
Nothing => "nothing".into(),
|
|
589
|
+
Bool(true) => "yes".into(),
|
|
590
|
+
Bool(false) => "no".into(),
|
|
591
|
+
Dec(d) => { let t = d.to_fixed(None, false); if t.contains('.') { t.trim_end_matches('0').trim_end_matches('.').to_string() } else { t } }
|
|
592
|
+
List(items) => format!("[{}]", items.borrow().iter().map(show_s).collect::<Vec<_>>().join(", ")),
|
|
593
|
+
Tuple(items) => format!("[{}]", items.iter().map(show_s).collect::<Vec<_>>().join(", ")),
|
|
594
|
+
Map(m) => format!("{{{}}}", m.borrow().pairs().iter().map(|(k, x)| format!("{}: {}", show_s(k), show_s(x))).collect::<Vec<_>>().join(", ")),
|
|
595
|
+
Record(r) => { let r = r.borrow(); format!("{}({})", r.kind.py, r.kind.fields.iter().map(|(f, _)| format!("{}: {}", f.replace('_', " "), show_s(&r.get(f).unwrap_or(Nothing)))).collect::<Vec<_>>().join(", ")) }
|
|
596
|
+
Date(y, m, d) => iso(*y, *m, *d),
|
|
597
|
+
_ => py_str_s(v),
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/// Python's repr(v).
|
|
602
|
+
pub fn py_repr(v: &Value) -> String {
|
|
603
|
+
match v {
|
|
604
|
+
Text(s) => {
|
|
605
|
+
let q = if s.contains('\'') && !s.contains('"') { '"' } else { '\'' };
|
|
606
|
+
let mut out = String::new();
|
|
607
|
+
for ch in s.chars() {
|
|
608
|
+
let cp = ch as u32;
|
|
609
|
+
if ch == '\\' { out.push_str("\\\\"); }
|
|
610
|
+
else if ch == q { out.push('\\'); out.push(q); }
|
|
611
|
+
else if ch == '\n' { out.push_str("\\n"); }
|
|
612
|
+
else if ch == '\r' { out.push_str("\\r"); }
|
|
613
|
+
else if ch == '\t' { out.push_str("\\t"); }
|
|
614
|
+
else if cp < 0x20 || cp == 0x7f { let _ = write!(out, "\\x{:02x}", cp); }
|
|
615
|
+
else { out.push(ch); }
|
|
616
|
+
}
|
|
617
|
+
format!("{}{}{}", q, out, q)
|
|
618
|
+
}
|
|
619
|
+
Nothing => "None".into(),
|
|
620
|
+
Bool(b) => if *b { "True".into() } else { "False".into() },
|
|
621
|
+
Int(n) => n.to_string(),
|
|
622
|
+
Dec(d) => format!("Decimal('{}')", d.to_sci()),
|
|
623
|
+
Money(a) => format!("Money('{}')", a.to_fixed(None, false)),
|
|
624
|
+
List(items) => format!("[{}]", items.borrow().iter().map(py_repr).collect::<Vec<_>>().join(", ")),
|
|
625
|
+
Tuple(items) => if items.len() == 1 { format!("({},)", py_repr(&items[0])) } else { format!("({})", items.iter().map(py_repr).collect::<Vec<_>>().join(", ")) },
|
|
626
|
+
Map(m) => format!("{{{}}}", m.borrow().pairs().iter().map(|(k, x)| format!("{}: {}", py_repr(k), py_repr(x))).collect::<Vec<_>>().join(", ")),
|
|
627
|
+
Date(y, m, d) => format!("datetime.date({}, {}, {})", y, m, d),
|
|
628
|
+
Record(r) => { let r = r.borrow(); format!("{}({})", r.kind.py, r.kind.fields.iter().map(|(f, _)| format!("{}={}", f, py_repr(&r.get(f).unwrap_or(Nothing)))).collect::<Vec<_>>().join(", ")) }
|
|
629
|
+
NotGiven => "not given".into(),
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/// Python's str(v).
|
|
634
|
+
pub fn py_str_s(v: &Value) -> String {
|
|
635
|
+
match v {
|
|
636
|
+
Text(s) => s.to_string(),
|
|
637
|
+
Money(_) => money_str(v),
|
|
638
|
+
Date(y, m, d) => iso(*y, *m, *d),
|
|
639
|
+
Dec(d) => d.to_sci(),
|
|
640
|
+
_ => py_repr(v),
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
pub fn show(v: Value) -> Value { string(show_s(&v)) }
|
|
644
|
+
/// Text with holes: the parts, already turned into text, joined.
|
|
645
|
+
pub fn cat(parts: Vec<Value>) -> Value { let mut s = String::new(); for p in parts { if let Text(t) = p { s.push_str(&t); } } string(s) }
|
|
646
|
+
pub fn len_of(v: Value) -> Value { py_len(&v) }
|
|
647
|
+
pub fn is_nothing(v: Value) -> bool { matches!(v, Nothing) }
|
|
648
|
+
pub fn tuple_at(v: Value, i: usize) -> Value { match &v { Tuple(t) => t[i].clone(), List(l) => l.borrow()[i].clone(), _ => Nothing } }
|
|
649
|
+
/// Stop with "message".
|
|
650
|
+
pub fn stop_with(v: Value) -> ! { Stop(py_str_s(&v)) }
|
|
651
|
+
pub fn py_str(v: Value) -> Value { string(py_str_s(&v)) }
|
|
652
|
+
|
|
653
|
+
/// Python's truth value (used only where the generated Python uses it: "where" conditions and Never rules).
|
|
654
|
+
pub fn truthy(v: &Value) -> bool {
|
|
655
|
+
match v {
|
|
656
|
+
Nothing | Bool(false) => false,
|
|
657
|
+
Bool(true) => true,
|
|
658
|
+
Int(n) => !n.is_zero(),
|
|
659
|
+
Dec(d) => !d.is_zero(),
|
|
660
|
+
Text(s) => !s.is_empty(),
|
|
661
|
+
List(l) => !l.borrow().is_empty(),
|
|
662
|
+
Tuple(t) => !t.is_empty(),
|
|
663
|
+
Map(m) => m.borrow().len() > 0,
|
|
664
|
+
_ => true,
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/// yes_no(v): a condition needs a real yes/no value.
|
|
669
|
+
pub fn yes_no(v: Value) -> bool {
|
|
670
|
+
if let Bool(b) = v { return b; }
|
|
671
|
+
kind_mismatch(format!("This needs a yes/no value, but it is {}. Compare it instead, for example: is 0, is empty, is nothing.", describe(&v)))
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/// _decimal(x) in thunder_runtime.py.
|
|
675
|
+
fn to_dec(x: &Value) -> Dec {
|
|
676
|
+
match x {
|
|
677
|
+
Dec(d) => d.clone(),
|
|
678
|
+
Bool(_) => kind_mismatch("A yes/no value was used where a number was needed.".into()),
|
|
679
|
+
Int(n) => Dec::int(n),
|
|
680
|
+
Nothing => kind_mismatch("A value was nothing where a number was needed.".into()),
|
|
681
|
+
_ => kind_mismatch(format!("{} was used where a number was needed.", describe(x))),
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
// ── Money ──────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
686
|
+
|
|
687
|
+
fn money_of(x: &Value) -> Value {
|
|
688
|
+
match x {
|
|
689
|
+
Money(_) => x.clone(),
|
|
690
|
+
Text(s) => {
|
|
691
|
+
let cleaned = s.replace(',', "").replace('$', "");
|
|
692
|
+
match Dec::parse(cleaned.trim()) { Some(d) => Money(d), None => raise(py_err("InvalidOperation", "[<class 'decimal.ConversionSyntax'>]".into())) }
|
|
693
|
+
}
|
|
694
|
+
_ => Money(to_dec(x)),
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/// Money._other: the amount of the other side, or a clear error.
|
|
699
|
+
fn money_other(other: &Value, verb: &str) -> Dec {
|
|
700
|
+
if let Money(a) = other { return a.clone(); }
|
|
701
|
+
if is_number(other) && num_cmp(other, &Int(BigInt::zero())) == Ordering::Equal { return Dec::int(&BigInt::zero()); }
|
|
702
|
+
kind_mismatch(format!("I can't {} money and {}. Write the number as money, for example $5.", verb, describe(other)))
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
// ── Map keys ───────────────────────────────────────────────────────────────────────────────────────────────────
|
|
706
|
+
|
|
707
|
+
fn key_of(k: &Value) -> String {
|
|
708
|
+
match k {
|
|
709
|
+
Nothing => "N".into(),
|
|
710
|
+
Text(s) => format!("s{}", s),
|
|
711
|
+
Bool(_) | Int(_) | Dec(_) => format!("n{}", dec_of(k).key()),
|
|
712
|
+
Money(a) => format!("m{}", a.key()),
|
|
713
|
+
Date(y, m, d) => format!("d{}", iso(*y, *m, *d)),
|
|
714
|
+
Tuple(items) => format!("t({})", items.iter().map(key_of).collect::<Vec<_>>().join(",")),
|
|
715
|
+
NotGiven => "G".into(),
|
|
716
|
+
_ => type_err(format!("unhashable type: '{}'", type_name(k))),
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
// ── Python operators ───────────────────────────────────────────────────────────────────────────────────────────
|
|
721
|
+
|
|
722
|
+
pub fn py_len(v: &Value) -> Value {
|
|
723
|
+
match v {
|
|
724
|
+
Text(s) => int_n(s.chars().count() as i64),
|
|
725
|
+
List(l) => int_n(l.borrow().len() as i64),
|
|
726
|
+
Tuple(t) => int_n(t.len() as i64),
|
|
727
|
+
Map(m) => int_n(m.borrow().len() as i64),
|
|
728
|
+
_ => type_err(format!("object of type '{}' has no len()", type_name(v))),
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/// Iterate a value the way Python's for loop does.
|
|
733
|
+
pub fn py_iter(v: Value) -> Vec<Value> {
|
|
734
|
+
match &v {
|
|
735
|
+
List(l) => l.borrow().clone(),
|
|
736
|
+
Tuple(t) => t.as_ref().clone(),
|
|
737
|
+
Text(s) => s.chars().map(|c| string(c.to_string())).collect(),
|
|
738
|
+
Map(m) => m.borrow().keys(),
|
|
739
|
+
_ => type_err(format!("'{}' object is not iterable", type_name(&v))),
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
pub fn py_list(v: Value) -> Value { list(py_iter(v)) }
|
|
743
|
+
|
|
744
|
+
pub fn add(a: Value, b: Value) -> Value {
|
|
745
|
+
if let Money(x) = &a { return Money(Dec::add(x, &money_other(&b, "add"))); }
|
|
746
|
+
if let Money(y) = &b { return Money(Dec::add(y, &money_other(&a, "add"))); }
|
|
747
|
+
if is_int_like(&a) && is_int_like(&b) { return Int(as_big(&a).add(&as_big(&b))); }
|
|
748
|
+
if is_num_like(&a) && is_num_like(&b) { return Dec(Dec::add(&dec_of(&a), &dec_of(&b))); }
|
|
749
|
+
match (&a, &b) {
|
|
750
|
+
(Text(x), Text(y)) => return string(format!("{}{}", x, y)),
|
|
751
|
+
(Text(_), _) => type_err(format!("can only concatenate str (not \"{}\") to str", type_name(&b))),
|
|
752
|
+
(List(x), List(y)) => { let mut v = x.borrow().clone(); v.extend(y.borrow().iter().cloned()); return list(v); }
|
|
753
|
+
(List(_), _) => type_err(format!("can only concatenate list (not \"{}\") to list", type_name(&b))),
|
|
754
|
+
(Tuple(x), Tuple(y)) => { let mut v = x.as_ref().clone(); v.extend(y.iter().cloned()); return tuple(v); }
|
|
755
|
+
(Tuple(_), _) => type_err(format!("can only concatenate tuple (not \"{}\") to tuple", type_name(&b))),
|
|
756
|
+
_ => type_err(format!("unsupported operand type(s) for +: '{}' and '{}'", type_name(&a), type_name(&b))),
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
pub fn sub(a: Value, b: Value) -> Value {
|
|
761
|
+
if let Money(x) = &a { return Money(Dec::sub(x, &money_other(&b, "subtract"))); }
|
|
762
|
+
if let Money(y) = &b { return Money(Dec::sub(&money_other(&a, "subtract"), y)); }
|
|
763
|
+
if is_int_like(&a) && is_int_like(&b) { return Int(as_big(&a).sub(&as_big(&b))); }
|
|
764
|
+
if is_num_like(&a) && is_num_like(&b) { return Dec(Dec::sub(&dec_of(&a), &dec_of(&b))); }
|
|
765
|
+
type_err(format!("unsupported operand type(s) for -: '{}' and '{}'", type_name(&a), type_name(&b)))
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
fn repeat(seq: &Value, n: &Value) -> Value {
|
|
769
|
+
let k = as_big(n).to_i64().unwrap_or(0);
|
|
770
|
+
match seq {
|
|
771
|
+
Text(s) => string(if k > 0 { s.repeat(k as usize) } else { String::new() }),
|
|
772
|
+
List(l) => { let items = l.borrow(); let mut out = Vec::new(); for _ in 0..k.max(0) { out.extend(items.iter().cloned()); } list(out) }
|
|
773
|
+
_ => Nothing,
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
pub fn mul(a: Value, b: Value) -> Value {
|
|
778
|
+
if let Money(x) = &a { if matches!(b, Money(_)) { kind_mismatch("Money can't be multiplied by money.".into()) } return Money(Dec::mul(x, &to_dec(&b))); }
|
|
779
|
+
if let Money(y) = &b { return Money(Dec::mul(y, &to_dec(&a))); }
|
|
780
|
+
if is_int_like(&a) && is_int_like(&b) { return Int(as_big(&a).mul(&as_big(&b))); }
|
|
781
|
+
if is_num_like(&a) && is_num_like(&b) { return Dec(Dec::mul(&dec_of(&a), &dec_of(&b))); }
|
|
782
|
+
let seq = |x: &Value| matches!(x, Text(_) | List(_));
|
|
783
|
+
if seq(&a) { if is_int_like(&b) { return repeat(&a, &b); } type_err(format!("can't multiply sequence by non-int of type '{}'", type_name(&b))) }
|
|
784
|
+
if seq(&b) { if is_int_like(&a) { return repeat(&b, &a); } type_err(format!("can't multiply sequence by non-int of type '{}'", type_name(&a))) }
|
|
785
|
+
type_err(format!("unsupported operand type(s) for *: '{}' and '{}'", type_name(&a), type_name(&b)))
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
pub fn neg(a: Value) -> Value {
|
|
789
|
+
match &a {
|
|
790
|
+
Money(x) => Money(x.neg()),
|
|
791
|
+
Int(_) | Bool(_) => Int(as_big(&a).negate()),
|
|
792
|
+
Dec(d) => Dec(d.neg()),
|
|
793
|
+
_ => type_err(format!("bad operand type for unary -: '{}'", type_name(&a))),
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/// Python's % on two whole numbers: the sign of the divisor.
|
|
798
|
+
pub fn int_mod(a: Value, b: Value) -> Value {
|
|
799
|
+
if !is_int_like(&a) || !is_int_like(&b) {
|
|
800
|
+
if is_num_like(&a) && is_num_like(&b) { return modulo(a, b); }
|
|
801
|
+
type_err(format!("unsupported operand type(s) for %: '{}' and '{}'", type_name(&a), type_name(&b)))
|
|
802
|
+
}
|
|
803
|
+
let (x, y) = (as_big(&a), as_big(&b));
|
|
804
|
+
if y.is_zero() { raise(py_err("ZeroDivisionError", "integer modulo by zero".into())) }
|
|
805
|
+
let mut r = x.divrem(&y).1;
|
|
806
|
+
if !r.is_zero() && r.is_neg() != y.is_neg() { r = r.add(&y); }
|
|
807
|
+
Int(r)
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
/// divide(a, b) in thunder_runtime.py: always exact.
|
|
811
|
+
pub fn divide(a: Value, b: Value) -> Value {
|
|
812
|
+
if let Money(x) = &a {
|
|
813
|
+
if let Money(y) = &b { if y.is_zero() { divided_by_zero() } return Dec(Dec::div(x, y)); }
|
|
814
|
+
let d = to_dec(&b);
|
|
815
|
+
if d.is_zero() { divided_by_zero() }
|
|
816
|
+
return Money(Dec::div(x, &d));
|
|
817
|
+
}
|
|
818
|
+
if matches!(b, Money(_)) { kind_mismatch("A plain number can't be divided by money.".into()) }
|
|
819
|
+
let (x, y) = (to_dec(&a), to_dec(&b));
|
|
820
|
+
if y.is_zero() { divided_by_zero() }
|
|
821
|
+
Dec(Dec::div(&x, &y))
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/// modulo(a, b) in thunder_runtime.py.
|
|
825
|
+
pub fn modulo(a: Value, b: Value) -> Value {
|
|
826
|
+
let money = matches!(a, Money(_));
|
|
827
|
+
let x = if let Money(m) = &a { m.clone() } else { to_dec(&a) };
|
|
828
|
+
let y = if let Money(m) = &b { m.clone() } else { to_dec(&b) };
|
|
829
|
+
if y.is_zero() { divided_by_zero() }
|
|
830
|
+
let mut r = Dec::rem(&x, &y);
|
|
831
|
+
if !r.is_zero() && r.s != (y.s && !y.is_zero()) { r = Dec::add(&r, &y); }
|
|
832
|
+
if money { return Money(r); }
|
|
833
|
+
if is_int(&a) && is_int(&b) { Int(r.to_bigint()) } else { Dec(r) }
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/// round_to(x, places).
|
|
837
|
+
pub fn round_to(x: Value, places: Value) -> Value {
|
|
838
|
+
let p = match &places { Dec(d) => d.to_bigint().to_i64().unwrap_or(0), _ => as_big(&places).to_i64().unwrap_or(0) };
|
|
839
|
+
if let Money(m) = &x { return Money(m.quantize_half_up(-p)); }
|
|
840
|
+
if is_int(&x) { return x; }
|
|
841
|
+
let d = to_dec(&x).quantize_half_up(-p);
|
|
842
|
+
if p == 0 { Int(d.to_bigint()) } else { Dec(d) }
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
fn same(a: &Value, b: &Value) -> bool {
|
|
846
|
+
match (a, b) {
|
|
847
|
+
(Nothing, Nothing) | (NotGiven, NotGiven) => true,
|
|
848
|
+
(Bool(x), Bool(y)) => x == y,
|
|
849
|
+
(Int(x), Int(y)) => x == y,
|
|
850
|
+
(Text(x), Text(y)) => x == y,
|
|
851
|
+
(List(x), List(y)) => Rc::ptr_eq(x, y),
|
|
852
|
+
(Map(x), Map(y)) => Rc::ptr_eq(x, y),
|
|
853
|
+
(Record(x), Record(y)) => Rc::ptr_eq(x, y),
|
|
854
|
+
_ => false,
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
/// Python ==.
|
|
859
|
+
pub fn eq_v(a: &Value, b: &Value) -> bool {
|
|
860
|
+
if same(a, b) { return true; }
|
|
861
|
+
if matches!(a, Money(_)) || matches!(b, Money(_)) {
|
|
862
|
+
let (m, o) = if let Money(m) = a { (m, b) } else if let Money(m) = b { (m, a) } else { unreachable!() };
|
|
863
|
+
if matches!(o, Nothing | Text(_) | Bool(_)) { return false; }
|
|
864
|
+
return Dec::cmp(m, &money_other(o, "compare")) == Ordering::Equal;
|
|
865
|
+
}
|
|
866
|
+
if matches!(a, Nothing) || matches!(b, Nothing) { return false; }
|
|
867
|
+
if is_num_like(a) && is_num_like(b) { return num_cmp(a, b) == Ordering::Equal; }
|
|
868
|
+
if matches!(a, Text(_)) || matches!(b, Text(_)) { return false; }
|
|
869
|
+
match (a, b) {
|
|
870
|
+
(List(x), List(y)) => { let (x, y) = (x.borrow(), y.borrow()); x.len() == y.len() && x.iter().zip(y.iter()).all(|(p, q)| same(p, q) || eq_v(p, q)) }
|
|
871
|
+
(Tuple(x), Tuple(y)) => x.len() == y.len() && x.iter().zip(y.iter()).all(|(p, q)| eq_v(p, q)),
|
|
872
|
+
(Map(x), Map(y)) => { let (x, y) = (x.borrow(), y.borrow()); x.len() == y.len() && x.pairs().iter().all(|(k, v)| y.has(k) && eq_v(v, &y.get(k).unwrap())) }
|
|
873
|
+
(Record(x), Record(y)) => { let (x, y) = (x.borrow(), y.borrow()); Rc::ptr_eq(&x.kind, &y.kind) && x.kind.fields.iter().all(|(f, _)| eq_v(&x.get(f).unwrap_or(Nothing), &y.get(f).unwrap_or(Nothing))) }
|
|
874
|
+
(Date(a1, b1, c1), Date(a2, b2, c2)) => a1 == a2 && b1 == b2 && c1 == c2,
|
|
875
|
+
_ => false,
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
pub fn eq(a: Value, b: Value) -> Value { Bool(eq_v(&a, &b)) }
|
|
879
|
+
|
|
880
|
+
fn flip(op: &str) -> &str { match op { "<" => ">", ">" => "<", "<=" => ">=", ">=" => "<=", o => o } }
|
|
881
|
+
fn holds(op: &str, c: Ordering) -> bool { match op { "<" => c == Ordering::Less, ">" => c == Ordering::Greater, "<=" => c != Ordering::Greater, _ => c != Ordering::Less } }
|
|
882
|
+
|
|
883
|
+
/// Python <, >, <=, >= (and == / != through eq).
|
|
884
|
+
pub fn compare_v(op: &str, a: &Value, b: &Value) -> bool {
|
|
885
|
+
if op == "==" { return eq_v(a, b); }
|
|
886
|
+
if op == "!=" { return !eq_v(a, b); }
|
|
887
|
+
if matches!(a, Money(_)) || matches!(b, Money(_)) {
|
|
888
|
+
let (m, o, o2) = if let Money(m) = a { (m, b, op) } else if let Money(m) = b { (m, a, flip(op)) } else { unreachable!() };
|
|
889
|
+
if matches!(o, Nothing) { type_err(format!("'{}' not supported between instances of 'decimal.Decimal' and 'NoneType'", o2)) }
|
|
890
|
+
return holds(o2, Dec::cmp(m, &money_other(o, "compare")));
|
|
891
|
+
}
|
|
892
|
+
match order(a, b) {
|
|
893
|
+
Some(c) => holds(op, c),
|
|
894
|
+
None => type_err(format!("'{}' not supported between instances of '{}' and '{}'", op, type_name(a), type_name(b))),
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
pub fn compare(op: &str, a: Value, b: Value) -> Value { Bool(compare_v(op, &a, &b)) }
|
|
898
|
+
|
|
899
|
+
/// The order of two values, or None when Python cannot order them.
|
|
900
|
+
fn order(a: &Value, b: &Value) -> Option<Ordering> {
|
|
901
|
+
if is_num_like(a) && is_num_like(b) { return Some(num_cmp(a, b)); }
|
|
902
|
+
if let (Text(x), Text(y)) = (a, b) { return Some(x.as_str().cmp(y.as_str())); }
|
|
903
|
+
if let (Date(..), Date(..)) = (a, b) { return Some(date_num(a).cmp(&date_num(b))); }
|
|
904
|
+
let seq = |v: &Value| -> Option<Vec<Value>> { match v { List(l) => Some(l.borrow().clone()), Tuple(t) => Some(t.as_ref().clone()), _ => None } };
|
|
905
|
+
if let (Some(x), Some(y)) = (seq(a), seq(b)) {
|
|
906
|
+
if matches!(a, List(_)) == matches!(b, List(_)) {
|
|
907
|
+
for i in 0..x.len().min(y.len()) {
|
|
908
|
+
if eq_v(&x[i], &y[i]) { continue; }
|
|
909
|
+
return Some(if compare_v("<", &x[i], &y[i]) { Ordering::Less } else { Ordering::Greater });
|
|
910
|
+
}
|
|
911
|
+
return Some(x.len().cmp(&y.len()));
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
None
|
|
915
|
+
}
|
|
916
|
+
fn date_num(v: &Value) -> i64 { if let Date(y, m, d) = v { y * 10000 + m * 100 + d } else { 0 } }
|
|
917
|
+
|
|
918
|
+
/// Python's `item in container`.
|
|
919
|
+
pub fn contains_v(container: &Value, item: &Value) -> bool {
|
|
920
|
+
match container {
|
|
921
|
+
Text(s) => { if let Text(t) = item { s.contains(t.as_str()) } else { type_err(format!("'in <string>' requires string as left operand, not {}", type_name(item))) } }
|
|
922
|
+
Map(m) => m.borrow().has(item),
|
|
923
|
+
List(l) => l.borrow().iter().any(|x| same(x, item) || eq_v(x, item)),
|
|
924
|
+
Tuple(t) => t.iter().any(|x| eq_v(x, item)),
|
|
925
|
+
_ => type_err(format!("argument of type '{}' is not iterable", type_name(container))),
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
/// `item in container`, with the item worked out first (as Python does).
|
|
929
|
+
pub fn is_in(item: Value, container: Value) -> Value { Bool(contains_v(&container, &item)) }
|
|
930
|
+
|
|
931
|
+
/// Python's list.sort / sorted: stable, using < only.
|
|
932
|
+
pub fn py_sort_with(items: Vec<Value>, key: Option<&dyn Fn(Value) -> Value>, reverse: bool) -> Vec<Value> {
|
|
933
|
+
let mut keyed: Vec<(Value, Value, usize)> = items.into_iter().enumerate().map(|(i, v)| { let k = match key { Some(f) => f(v.clone()), None => v.clone() }; (v, k, i) }).collect();
|
|
934
|
+
// A merge sort that calls compare (which can fail) the way JavaScript's stable sort does with this comparator.
|
|
935
|
+
let cmp = |x: &(Value, Value, usize), y: &(Value, Value, usize)| -> Ordering {
|
|
936
|
+
let (l, r) = if reverse { (&y.1, &x.1) } else { (&x.1, &y.1) };
|
|
937
|
+
if compare_v("<", l, r) { return Ordering::Less; }
|
|
938
|
+
let (l2, r2) = if reverse { (&x.1, &y.1) } else { (&y.1, &x.1) };
|
|
939
|
+
if compare_v("<", l2, r2) { return Ordering::Greater; }
|
|
940
|
+
x.2.cmp(&y.2)
|
|
941
|
+
};
|
|
942
|
+
merge_sort(&mut keyed, &cmp);
|
|
943
|
+
keyed.into_iter().map(|x| x.0).collect()
|
|
944
|
+
}
|
|
945
|
+
fn merge_sort<T: Clone>(v: &mut Vec<T>, cmp: &dyn Fn(&T, &T) -> Ordering) {
|
|
946
|
+
let n = v.len();
|
|
947
|
+
if n < 2 { return; }
|
|
948
|
+
// Short lists, as TimSort (Python's and V8's) sorts them, comparing in the same order so that a comparison that
|
|
949
|
+
// fails (mixed kinds) fails the same way: count the first run, then binary insertion for the rest.
|
|
950
|
+
if n <= 64 {
|
|
951
|
+
let mut run = 2;
|
|
952
|
+
let descending = cmp(&v[1], &v[0]) == Ordering::Less;
|
|
953
|
+
while run < n {
|
|
954
|
+
let o = cmp(&v[run], &v[run - 1]);
|
|
955
|
+
if descending { if o != Ordering::Less { break; } } else if o == Ordering::Less { break; }
|
|
956
|
+
run += 1;
|
|
957
|
+
}
|
|
958
|
+
if descending { v[..run].reverse(); }
|
|
959
|
+
for start in run..n {
|
|
960
|
+
let pivot = v[start].clone();
|
|
961
|
+
let (mut left, mut right) = (0, start);
|
|
962
|
+
while left < right {
|
|
963
|
+
let mid = left + ((right - left) >> 1);
|
|
964
|
+
if cmp(&pivot, &v[mid]) == Ordering::Less { right = mid; } else { left = mid + 1; }
|
|
965
|
+
}
|
|
966
|
+
let mut k = start;
|
|
967
|
+
while k > left { v[k] = v[k - 1].clone(); k -= 1; }
|
|
968
|
+
v[left] = pivot;
|
|
969
|
+
}
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
let mid = n / 2;
|
|
973
|
+
let mut a = v[..mid].to_vec();
|
|
974
|
+
let mut b = v[mid..].to_vec();
|
|
975
|
+
merge_sort(&mut a, cmp);
|
|
976
|
+
merge_sort(&mut b, cmp);
|
|
977
|
+
let (mut i, mut j, mut k) = (0, 0, 0);
|
|
978
|
+
while i < a.len() && j < b.len() { if cmp(&b[j], &a[i]) == Ordering::Less { v[k] = b[j].clone(); j += 1; } else { v[k] = a[i].clone(); i += 1; } k += 1; }
|
|
979
|
+
while i < a.len() { v[k] = a[i].clone(); i += 1; k += 1; }
|
|
980
|
+
while j < b.len() { v[k] = b[j].clone(); j += 1; k += 1; }
|
|
981
|
+
}
|
|
982
|
+
pub fn py_sort(items: Value, key: Option<Box<dyn Fn(Value) -> Value>>, reverse: bool) -> Value {
|
|
983
|
+
list(py_sort_with(py_iter(items), key.as_deref(), reverse))
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
// ── Attribute-style Python calls the generated code makes on values ────────────────────────────────────────────
|
|
987
|
+
|
|
988
|
+
fn attr_err(v: &Value, name: &str) -> TErr { py_err("AttributeError", format!("'{}' object has no attribute '{}'", type_name(v), name)) }
|
|
989
|
+
fn str_method(v: &Value, name: &str) -> String { if let Text(s) = v { s.to_string() } else { raise(attr_err(v, name)) } }
|
|
990
|
+
|
|
991
|
+
fn is_split_line(c: char) -> bool { matches!(c, '\n' | '\r' | '\u{0b}' | '\u{0c}' | '\u{1c}' | '\u{1d}' | '\u{1e}' | '\u{85}' | '\u{2028}' | '\u{2029}') }
|
|
992
|
+
fn split_lines(s: &str) -> Vec<Value> {
|
|
993
|
+
let chars: Vec<char> = s.chars().collect();
|
|
994
|
+
let mut out = Vec::new();
|
|
995
|
+
let mut cur = String::new();
|
|
996
|
+
let mut i = 0;
|
|
997
|
+
while i < chars.len() {
|
|
998
|
+
let c = chars[i];
|
|
999
|
+
if is_split_line(c) {
|
|
1000
|
+
out.push(string(std::mem::take(&mut cur)));
|
|
1001
|
+
if c == '\r' && i + 1 < chars.len() && chars[i + 1] == '\n' { i += 1; }
|
|
1002
|
+
} else { cur.push(c); }
|
|
1003
|
+
i += 1;
|
|
1004
|
+
}
|
|
1005
|
+
if !cur.is_empty() { out.push(string(cur)); }
|
|
1006
|
+
out
|
|
1007
|
+
}
|
|
1008
|
+
/// JavaScript's \s, plus the separators Python's str.split/strip also treat as space.
|
|
1009
|
+
fn is_py_space(c: char) -> bool {
|
|
1010
|
+
matches!(c, '\t' | '\n' | '\u{0b}' | '\u{0c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'..='\u{200a}' | '\u{2028}' | '\u{2029}' | '\u{202f}' | '\u{205f}' | '\u{3000}' | '\u{feff}' | '\u{1c}'..='\u{1f}' | '\u{85}')
|
|
1011
|
+
}
|
|
1012
|
+
fn py_split(s: &str) -> Vec<String> { s.split(is_py_space).filter(|x| !x.is_empty()).map(|x| x.to_string()).collect() }
|
|
1013
|
+
fn py_strip(s: &str) -> String { s.trim_matches(is_py_space).to_string() }
|
|
1014
|
+
|
|
1015
|
+
// ── JSON, the way Python's json module reads and writes it ─────────────────────────────────────────────────────
|
|
1016
|
+
|
|
1017
|
+
struct JsonErr { msg: String, pos: usize }
|
|
1018
|
+
|
|
1019
|
+
fn json_parse(text: &str) -> Value {
|
|
1020
|
+
let s: Vec<char> = text.chars().collect();
|
|
1021
|
+
// Positions in the message are in UTF-16 units, as JavaScript counts them.
|
|
1022
|
+
fn ws(s: &[char], mut i: usize) -> usize { while i < s.len() && matches!(s[i], ' ' | '\t' | '\n' | '\r') { i += 1; } i }
|
|
1023
|
+
fn st(s: &[char], begin: usize) -> Result<(String, usize), JsonErr> {
|
|
1024
|
+
let mut i = begin + 1;
|
|
1025
|
+
let mut out = String::new();
|
|
1026
|
+
loop {
|
|
1027
|
+
if i >= s.len() { return Err(JsonErr { msg: "Unterminated string starting at".into(), pos: begin }); }
|
|
1028
|
+
let ch = s[i];
|
|
1029
|
+
if ch == '"' { return Ok((out, i + 1)); }
|
|
1030
|
+
if (ch as u32) < 0x20 { return Err(JsonErr { msg: "Invalid control character at".into(), pos: i }); }
|
|
1031
|
+
if ch != '\\' { out.push(ch); i += 1; continue; }
|
|
1032
|
+
if i + 1 >= s.len() { return Err(JsonErr { msg: "Unterminated string starting at".into(), pos: begin }); }
|
|
1033
|
+
let esc = s[i + 1];
|
|
1034
|
+
let simple = match esc { '"' => Some('"'), '\\' => Some('\\'), '/' => Some('/'), 'b' => Some('\u{8}'), 'f' => Some('\u{c}'), 'n' => Some('\n'), 'r' => Some('\r'), 't' => Some('\t'), _ => None };
|
|
1035
|
+
if let Some(c) = simple { out.push(c); i += 2; continue; }
|
|
1036
|
+
if esc != 'u' { return Err(JsonErr { msg: "Invalid \\escape".into(), pos: i }); }
|
|
1037
|
+
let hex: String = s[(i + 2).min(s.len())..(i + 6).min(s.len())].iter().collect();
|
|
1038
|
+
if hex.len() != 4 || !hex.chars().all(|c| c.is_ascii_hexdigit()) { return Err(JsonErr { msg: "Invalid \\uXXXX escape".into(), pos: i + 1 }); }
|
|
1039
|
+
let mut cp = u32::from_str_radix(&hex, 16).unwrap();
|
|
1040
|
+
i += 6;
|
|
1041
|
+
if (0xd800..=0xdbff).contains(&cp) && i + 1 < s.len() && s[i] == '\\' && s[i + 1] == 'u' {
|
|
1042
|
+
let lo_hex: String = s[(i + 2).min(s.len())..(i + 6).min(s.len())].iter().collect();
|
|
1043
|
+
if lo_hex.len() == 4 && lo_hex.chars().all(|c| c.is_ascii_hexdigit()) {
|
|
1044
|
+
let lo = u32::from_str_radix(&lo_hex, 16).unwrap();
|
|
1045
|
+
if (0xdc00..=0xdfff).contains(&lo) { cp = 0x10000 + ((cp - 0xd800) << 10) + (lo - 0xdc00); i += 6; }
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
out.push(char::from_u32(cp).unwrap_or('\u{fffd}'));
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
fn num(s: &[char], i: usize) -> Option<(String, bool, usize)> {
|
|
1052
|
+
let mut j = i;
|
|
1053
|
+
if j < s.len() && s[j] == '-' { j += 1; }
|
|
1054
|
+
if j >= s.len() || !s[j].is_ascii_digit() { return None; }
|
|
1055
|
+
if s[j] == '0' { j += 1; } else { while j < s.len() && s[j].is_ascii_digit() { j += 1; } }
|
|
1056
|
+
let mut frac = false;
|
|
1057
|
+
if j + 1 < s.len() && s[j] == '.' && s[j + 1].is_ascii_digit() { frac = true; j += 1; while j < s.len() && s[j].is_ascii_digit() { j += 1; } }
|
|
1058
|
+
if j < s.len() && (s[j] == 'e' || s[j] == 'E') {
|
|
1059
|
+
let mut k = j + 1;
|
|
1060
|
+
if k < s.len() && (s[k] == '+' || s[k] == '-') { k += 1; }
|
|
1061
|
+
if k < s.len() && s[k].is_ascii_digit() { while k < s.len() && s[k].is_ascii_digit() { k += 1; } frac = true; j = k; }
|
|
1062
|
+
}
|
|
1063
|
+
Some((s[i..j].iter().collect(), frac, j))
|
|
1064
|
+
}
|
|
1065
|
+
fn starts(s: &[char], i: usize, w: &str) -> bool { let w: Vec<char> = w.chars().collect(); i + w.len() <= s.len() && s[i..i + w.len()] == w[..] }
|
|
1066
|
+
fn value(s: &[char], i: usize) -> Result<(Value, usize), JsonErr> {
|
|
1067
|
+
if i >= s.len() { return Err(JsonErr { msg: "Expecting value".into(), pos: i }); }
|
|
1068
|
+
let ch = s[i];
|
|
1069
|
+
if ch == '"' { let (t, j) = st(s, i)?; return Ok((string(t), j)); }
|
|
1070
|
+
if ch == '{' { return obj(s, i + 1); }
|
|
1071
|
+
if ch == '[' { return arr(s, i + 1); }
|
|
1072
|
+
if starts(s, i, "null") { return Ok((Nothing, i + 4)); }
|
|
1073
|
+
if starts(s, i, "true") { return Ok((Bool(true), i + 4)); }
|
|
1074
|
+
if starts(s, i, "false") { return Ok((Bool(false), i + 5)); }
|
|
1075
|
+
if let Some((t, frac, j)) = num(s, i) { return Ok((if frac { Dec(Dec::parse(&t).unwrap()) } else { Int(BigInt::parse(&t).unwrap()) }, j)); }
|
|
1076
|
+
Err(JsonErr { msg: "Expecting value".into(), pos: i })
|
|
1077
|
+
}
|
|
1078
|
+
fn obj(s: &[char], i: usize) -> Result<(Value, usize), JsonErr> {
|
|
1079
|
+
let mut d = PyDict::new();
|
|
1080
|
+
let mut i = ws(s, i);
|
|
1081
|
+
if i < s.len() && s[i] == '}' { return Ok((Map(Rc::new(RefCell::new(d))), i + 1)); }
|
|
1082
|
+
loop {
|
|
1083
|
+
if i >= s.len() || s[i] != '"' { return Err(JsonErr { msg: "Expecting property name enclosed in double quotes".into(), pos: i }); }
|
|
1084
|
+
let (k, j) = st(s, i)?;
|
|
1085
|
+
i = ws(s, j);
|
|
1086
|
+
if i >= s.len() || s[i] != ':' { return Err(JsonErr { msg: "Expecting ':' delimiter".into(), pos: i }); }
|
|
1087
|
+
i = ws(s, i + 1);
|
|
1088
|
+
let (v, j) = value(s, i)?;
|
|
1089
|
+
d.set(string(k), v);
|
|
1090
|
+
i = ws(s, j);
|
|
1091
|
+
if i < s.len() && s[i] == '}' { return Ok((Map(Rc::new(RefCell::new(d))), i + 1)); }
|
|
1092
|
+
if i >= s.len() || s[i] != ',' { return Err(JsonErr { msg: "Expecting ',' delimiter".into(), pos: i }); }
|
|
1093
|
+
let comma = i;
|
|
1094
|
+
i = ws(s, i + 1);
|
|
1095
|
+
if i < s.len() && s[i] == '}' { return Err(JsonErr { msg: "Illegal trailing comma before end of object".into(), pos: comma }); }
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
fn arr(s: &[char], i: usize) -> Result<(Value, usize), JsonErr> {
|
|
1099
|
+
let mut out = Vec::new();
|
|
1100
|
+
let mut i = ws(s, i);
|
|
1101
|
+
if i < s.len() && s[i] == ']' { return Ok((list(out), i + 1)); }
|
|
1102
|
+
loop {
|
|
1103
|
+
let (v, j) = value(s, i)?;
|
|
1104
|
+
out.push(v);
|
|
1105
|
+
i = ws(s, j);
|
|
1106
|
+
if i < s.len() && s[i] == ']' { return Ok((list(out), i + 1)); }
|
|
1107
|
+
if i >= s.len() || s[i] != ',' { return Err(JsonErr { msg: "Expecting ',' delimiter".into(), pos: i }); }
|
|
1108
|
+
let comma = i;
|
|
1109
|
+
i = ws(s, i + 1);
|
|
1110
|
+
if i < s.len() && s[i] == ']' { return Err(JsonErr { msg: "Illegal trailing comma before end of array".into(), pos: comma }); }
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
let result = (|| { let (v, end) = value(&s, ws(&s, 0))?; let end = ws(&s, end); if end != s.len() { return Err(JsonErr { msg: "Extra data".into(), pos: end }); } Ok(v) })();
|
|
1114
|
+
match result {
|
|
1115
|
+
Ok(v) => v,
|
|
1116
|
+
Err(e) => {
|
|
1117
|
+
let before = &s[..e.pos.min(s.len())];
|
|
1118
|
+
let line = before.iter().filter(|c| **c == '\n').count() + 1;
|
|
1119
|
+
let last_nl = before.iter().rposition(|c| *c == '\n');
|
|
1120
|
+
let u16len = |cs: &[char]| cs.iter().map(|c| c.len_utf16()).sum::<usize>();
|
|
1121
|
+
let col = match last_nl { Some(p) => u16len(&before[p + 1..]) + 1, None => u16len(before) + 1 };
|
|
1122
|
+
conversion_failed(format!("This is not JSON: {} (line {}, column {}).", e.msg, line, col))
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
fn json_ready(v: &Value) -> Value {
|
|
1128
|
+
match v {
|
|
1129
|
+
Nothing | Bool(_) | Text(_) | Int(_) | Dec(_) => v.clone(),
|
|
1130
|
+
Money(_) => kind_mismatch("Money has no JSON form of its own: use its amount, for example price's amount.".into()),
|
|
1131
|
+
List(l) => list(l.borrow().iter().map(json_ready).collect()),
|
|
1132
|
+
Tuple(t) => list(t.iter().map(json_ready).collect()),
|
|
1133
|
+
Map(m) => {
|
|
1134
|
+
let mut out = PyDict::new();
|
|
1135
|
+
for (k, x) in m.borrow().pairs() { if !matches!(k, Text(_)) { kind_mismatch(format!("A JSON object's keys are text, but one is {}.", describe(&k))) } out.set(k, json_ready(&x)); }
|
|
1136
|
+
Map(Rc::new(RefCell::new(out)))
|
|
1137
|
+
}
|
|
1138
|
+
Record(r) => { let r = r.borrow(); let mut out = PyDict::new(); for (f, _) in &r.kind.fields { out.set(text(f), json_ready(&r.get(f).unwrap_or(Nothing))); } Map(Rc::new(RefCell::new(out))) }
|
|
1139
|
+
_ => kind_mismatch(format!("{} has no JSON form.", describe(v))),
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
fn json_str(s: &str) -> String {
|
|
1144
|
+
let mut out = String::from("\"");
|
|
1145
|
+
for ch in s.chars() {
|
|
1146
|
+
let cp = ch as u32;
|
|
1147
|
+
match ch {
|
|
1148
|
+
'"' => out.push_str("\\\""),
|
|
1149
|
+
'\\' => out.push_str("\\\\"),
|
|
1150
|
+
'\n' => out.push_str("\\n"),
|
|
1151
|
+
'\r' => out.push_str("\\r"),
|
|
1152
|
+
'\t' => out.push_str("\\t"),
|
|
1153
|
+
'\u{8}' => out.push_str("\\b"),
|
|
1154
|
+
'\u{c}' => out.push_str("\\f"),
|
|
1155
|
+
_ if (0x20..=0x7e).contains(&cp) => out.push(ch),
|
|
1156
|
+
_ if cp > 0xffff => { let v = cp - 0x10000; let _ = write!(out, "\\u{:x}\\u{:x}", 0xd800 + (v >> 10), 0xdc00 + (v & 0x3ff)); }
|
|
1157
|
+
_ => { let _ = write!(out, "\\u{:04x}", cp); }
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
out.push('"');
|
|
1161
|
+
out
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
fn json_text(v: &Value) -> String {
|
|
1165
|
+
fn w(x: &Value) -> String {
|
|
1166
|
+
match x {
|
|
1167
|
+
Nothing => "null".into(),
|
|
1168
|
+
Bool(true) => "true".into(),
|
|
1169
|
+
Bool(false) => "false".into(),
|
|
1170
|
+
Int(n) => n.to_string(),
|
|
1171
|
+
Dec(d) => { let t = d.to_sci(); if d.is_integral() && t.contains('E') { d.to_fixed(None, false) } else { t } }
|
|
1172
|
+
Text(s) => json_str(s),
|
|
1173
|
+
List(l) => format!("[{}]", l.borrow().iter().map(w).collect::<Vec<_>>().join(", ")),
|
|
1174
|
+
Map(m) => format!("{{{}}}", m.borrow().pairs().iter().map(|(k, y)| format!("{}: {}", json_str(&py_str_s(k)), w(y))).collect::<Vec<_>>().join(", ")),
|
|
1175
|
+
_ => String::new(),
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
w(&json_ready(v))
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
// ── Frames: which Thunder line is running, for errors ──────────────────────────────────────────────────────────
|
|
1182
|
+
|
|
1183
|
+
pub const MAX_FRAMES: usize = 997; // as deep as the generated Python goes (recursion limit 1000, less its own frames)
|
|
1184
|
+
|
|
1185
|
+
thread_local! {
|
|
1186
|
+
static FRAMES: RefCell<Vec<(&'static str, i64)>> = RefCell::new(Vec::new());
|
|
1187
|
+
static OUT: RefCell<Vec<u8>> = RefCell::new(Vec::new());
|
|
1188
|
+
static ABORTED: RefCell<bool> = RefCell::new(false);
|
|
1189
|
+
static EXIT: RefCell<i32> = RefCell::new(0);
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
fn snapshot() -> Vec<(String, i64)> { FRAMES.with(|f| f.borrow().iter().map(|(file, line)| (file.to_string(), *line)).collect()) }
|
|
1193
|
+
fn depth() -> usize { FRAMES.with(|f| f.borrow().len()) }
|
|
1194
|
+
/// The line now running in the innermost frame.
|
|
1195
|
+
pub fn set_line(line: i64) { FRAMES.with(|f| { if let Some(top) = f.borrow_mut().last_mut() { top.1 = line; } }) }
|
|
1196
|
+
fn top_frame() -> (&'static str, i64) { FRAMES.with(|f| *f.borrow().last().unwrap_or(&("", 0))) }
|
|
1197
|
+
|
|
1198
|
+
/// Run `body`, catching a Thunder error (any other panic is a bug in the runtime, reported as one).
|
|
1199
|
+
pub fn catch<R>(body: impl FnOnce() -> R) -> Result<R, TErr> {
|
|
1200
|
+
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(body)) {
|
|
1201
|
+
Ok(v) => Ok(v),
|
|
1202
|
+
Err(payload) => Err(match payload.downcast::<TErr>() {
|
|
1203
|
+
Ok(e) => *e,
|
|
1204
|
+
Err(other) => {
|
|
1205
|
+
let msg = other.downcast_ref::<String>().cloned().or_else(|| other.downcast_ref::<&str>().map(|s| s.to_string())).unwrap_or_else(|| "the Rust runtime stopped".into());
|
|
1206
|
+
py_err("RuntimeError", msg)
|
|
1207
|
+
}
|
|
1208
|
+
}),
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
/// An error on its way out of a frame: remember where it happened (the innermost frames first seen).
|
|
1213
|
+
fn fail(mut e: TErr) -> TErr { if e.at.is_none() { e.at = Some(snapshot()); } e }
|
|
1214
|
+
|
|
1215
|
+
fn in_frame<R>(file: &'static str, line: i64, body: impl FnOnce() -> R) -> R {
|
|
1216
|
+
FRAMES.with(|f| f.borrow_mut().push((file, line)));
|
|
1217
|
+
let r = catch(body);
|
|
1218
|
+
match r {
|
|
1219
|
+
Ok(v) => { FRAMES.with(|f| { f.borrow_mut().pop(); }); v }
|
|
1220
|
+
Err(e) => { let e = fail(e); FRAMES.with(|f| { f.borrow_mut().pop(); }); raise(e) }
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
/// A frame for a program, a test, or a kept value (as the engine's withFrame).
|
|
1225
|
+
pub fn frame<R>(file: &'static str, line: i64, body: impl FnOnce() -> R) -> R {
|
|
1226
|
+
if depth() >= MAX_FRAMES { raise(py_err("RecursionError", "maximum recursion depth exceeded".into())) }
|
|
1227
|
+
in_frame(file, line, body)
|
|
1228
|
+
}
|
|
1229
|
+
/// A frame for a call; `first` is the Thunder line the function starts on (where Python stops when it is too deep).
|
|
1230
|
+
pub fn call<R>(file: &'static str, line: i64, first: Option<i64>, body: impl FnOnce() -> R) -> R {
|
|
1231
|
+
if depth() >= MAX_FRAMES {
|
|
1232
|
+
let mut err = py_err("RecursionError", "maximum recursion depth exceeded".into());
|
|
1233
|
+
if let Some(fl) = first { let mut w = snapshot(); w.push((file.to_string(), fl)); err.at = Some(w); }
|
|
1234
|
+
raise(err)
|
|
1235
|
+
}
|
|
1236
|
+
in_frame(file, line, body)
|
|
1237
|
+
}
|
|
1238
|
+
/// A key for sorting by a field: it runs in a frame at the sorting line, as the generated Python's lambda does.
|
|
1239
|
+
pub fn key_at(get: fn(Value) -> Value) -> Box<dyn Fn(Value) -> Value> {
|
|
1240
|
+
let (file, line) = top_frame();
|
|
1241
|
+
Box::new(move |item: Value| frame(file, line, || get(item)))
|
|
1242
|
+
}
|
|
1243
|
+
pub fn key_with(get: Box<dyn Fn(Value) -> Value>) -> Box<dyn Fn(Value) -> Value> {
|
|
1244
|
+
let (file, line) = top_frame();
|
|
1245
|
+
Box::new(move |item: Value| frame(file, line, || get(item)))
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
pub fn say(t: Value) { let s = match &t { Text(x) => x.to_string(), _ => show_s(&t) }; OUT.with(|o| { let mut o = o.borrow_mut(); o.extend_from_slice(s.as_bytes()); o.push(b'\n'); }); }
|
|
1249
|
+
fn flush() { OUT.with(|o| { let mut o = o.borrow_mut(); let mut out = std::io::stdout(); let _ = out.write_all(&o); let _ = out.flush(); o.clear(); }) }
|
|
1250
|
+
|
|
1251
|
+
// ── Records ────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
1252
|
+
|
|
1253
|
+
/// obj.name for a record field (a Python attribute), or Money's amount.
|
|
1254
|
+
pub fn get_attr(obj: Value, name: &str) -> Value {
|
|
1255
|
+
if let Record(r) = &obj { if let Some(v) = r.borrow().get(name) { return v; } }
|
|
1256
|
+
if let Money(a) = &obj { if name == "amount" { return Dec(a.clone()); } }
|
|
1257
|
+
raise(attr_err(&obj, name))
|
|
1258
|
+
}
|
|
1259
|
+
/// obj.name = value: the record's Never rules first, as its __setattr__ does.
|
|
1260
|
+
pub fn set_attr(obj: Value, name: &str, value: Value) {
|
|
1261
|
+
match &obj {
|
|
1262
|
+
Record(r) => {
|
|
1263
|
+
let kind = r.borrow().kind.clone();
|
|
1264
|
+
if let Some((_, rules)) = kind.rules.iter().find(|(f, _)| *f == name) { for rule in rules { never((rule.cond)(value.clone()), rule.text, rule.line, value.clone()); } }
|
|
1265
|
+
let mut rec = r.borrow_mut();
|
|
1266
|
+
if let Some(slot) = rec.f.iter_mut().find(|(k, _)| *k == name) { slot.1 = value; } else {
|
|
1267
|
+
let field = kind.fields.iter().find(|(f, _)| *f == name).map(|(f, _)| *f).unwrap_or("?");
|
|
1268
|
+
rec.f.push((field, value));
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
Money(_) => raise(py_err("AttributeError", "Money cannot be changed; make new money instead.".into())),
|
|
1272
|
+
_ => raise(attr_err(&obj, name)),
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
fn field_names(key: &str) -> [String; 4] { [key.to_string(), key.replace(' ', "_"), key.to_lowercase(), key.to_lowercase().replace(' ', "_")] }
|
|
1276
|
+
pub fn get_field(obj: Value, key: &str) -> Value {
|
|
1277
|
+
if matches!(obj, Nothing) { missing_value(format!("This value is nothing, so it has no {}.", key)) }
|
|
1278
|
+
let names = field_names(key);
|
|
1279
|
+
if let Map(m) = &obj {
|
|
1280
|
+
let m = m.borrow();
|
|
1281
|
+
for k in &names { let kv = text(k); if m.has(&kv) { return m.get(&kv).unwrap(); } }
|
|
1282
|
+
for (k, v) in m.pairs() { if py_strip(&py_str_s(&k)).to_lowercase() == key.to_lowercase() { return v; } }
|
|
1283
|
+
missing_value(format!("There is no field \"{}\". Fields here: {}.", key, m.keys().iter().map(py_str_s).collect::<Vec<_>>().join(", ")))
|
|
1284
|
+
}
|
|
1285
|
+
for k in &names {
|
|
1286
|
+
if let Record(r) = &obj { if let Some(v) = r.borrow().get(k) { return v; } }
|
|
1287
|
+
if let Money(a) = &obj { if k == "amount" { return Dec(a.clone()); } }
|
|
1288
|
+
}
|
|
1289
|
+
missing_value(format!("{} has no field \"{}\".", describe(&obj), key))
|
|
1290
|
+
}
|
|
1291
|
+
pub fn set_field(obj: Value, key: &str, value: Value) {
|
|
1292
|
+
if let Map(m) = &obj { m.borrow_mut().set(text(key), value); return; }
|
|
1293
|
+
for k in field_names(key) {
|
|
1294
|
+
if let Record(r) = &obj {
|
|
1295
|
+
let field = { let rb = r.borrow(); rb.kind.fields.iter().find(|(f, _)| *f == k).map(|(f, _)| *f) };
|
|
1296
|
+
if let Some(f) = field { if r.borrow().has(f) { set_attr(obj.clone(), f, value); return; } }
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
missing_value(format!("{} has no field \"{}\".", describe(&obj), key))
|
|
1300
|
+
}
|
|
1301
|
+
/// A record: the fields it is given, the others defaulted; each set through its Never rules.
|
|
1302
|
+
pub fn new_record(kind: Rc<Kind>, given: Vec<(&'static str, Value)>) -> Value {
|
|
1303
|
+
let rec = Rc::new(RefCell::new(Rec { kind: kind.clone(), f: Vec::new() }));
|
|
1304
|
+
let missing: Vec<&str> = kind.fields.iter().filter(|(f, k)| !given.iter().any(|(g, _)| g == f) && !["optional", "list", "map"].contains(k)).map(|(f, _)| *f).collect();
|
|
1305
|
+
if !missing.is_empty() {
|
|
1306
|
+
let names: Vec<String> = missing.iter().map(|f| format!("'{}'", f)).collect();
|
|
1307
|
+
type_err(format!("{}.__init__() missing {} required keyword-only argument{}: {}", kind.py, missing.len(), if missing.len() == 1 { "" } else { "s" }, names.join(if missing.len() == 2 { " and " } else { ", " })))
|
|
1308
|
+
}
|
|
1309
|
+
let obj = Record(rec);
|
|
1310
|
+
for (f, k) in &kind.fields {
|
|
1311
|
+
let v = match given.iter().find(|(g, _)| g == f) { Some((_, v)) => v.clone(), None => match *k { "optional" => Nothing, "list" => list(vec![]), _ => new_map() } };
|
|
1312
|
+
set_attr(obj.clone(), f, v);
|
|
1313
|
+
}
|
|
1314
|
+
obj
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
/// never(cond, text, rule, value): a broken Never rule stops the program.
|
|
1318
|
+
pub fn never(cond: Value, text: &str, line: i64, value: Value) {
|
|
1319
|
+
if truthy(&cond) { rule_broken(format!("{} (the rule on line {}), but the value is {}.", text, line, show_s(&value))) }
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
// ── Helpers the generated code calls ───────────────────────────────────────────────────────────────────────────
|
|
1323
|
+
|
|
1324
|
+
pub fn range_int(v: Value) -> i64 {
|
|
1325
|
+
match &v {
|
|
1326
|
+
Int(n) => n.to_i64().unwrap_or(i64::MAX),
|
|
1327
|
+
Bool(b) => if *b { 1 } else { 0 },
|
|
1328
|
+
_ => type_err(format!("'{}' object cannot be interpreted as an integer", match v { Dec(_) => "decimal.Decimal", Nothing => "NoneType", Money(_) => "Money", Text(_) => "str", _ => "object" })),
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
pub fn unpack2(el: Value) -> (Value, Value) {
|
|
1332
|
+
let items: Option<Vec<Value>> = match &el { List(l) => Some(l.borrow().clone()), Tuple(t) => Some(t.as_ref().clone()), Text(s) => Some(s.chars().map(|c| string(c.to_string())).collect()), Map(m) => Some(m.borrow().keys()), _ => None };
|
|
1333
|
+
let items = match items { Some(i) => i, None => type_err(format!("cannot unpack non-iterable {} object", match el { Nothing => "NoneType", Int(_) => "int", Dec(_) => "decimal.Decimal", Bool(_) => "bool", _ => "object" })) };
|
|
1334
|
+
if items.len() < 2 { raise(py_err("ValueError", format!("not enough values to unpack (expected 2, got {})", items.len()))) }
|
|
1335
|
+
if items.len() > 2 { raise(py_err("ValueError", format!("too many values to unpack (expected 2, got {})", items.len()))) }
|
|
1336
|
+
(items[0].clone(), items[1].clone())
|
|
1337
|
+
}
|
|
1338
|
+
pub fn map_items(m: Value) -> Vec<Value> { if let Map(d) = &m { d.borrow().pairs().into_iter().map(|(k, v)| tuple(vec![k, v])).collect() } else { raise(attr_err(&m, "items")) } }
|
|
1339
|
+
pub fn pairs_of(c: Value) -> Vec<Value> { if matches!(c, Map(_)) { map_items(c) } else { py_iter(c) } }
|
|
1340
|
+
|
|
1341
|
+
fn seq_items(v: &Value) -> Option<Vec<Value>> { match v { List(l) => Some(l.borrow().clone()), Tuple(t) => Some(t.as_ref().clone()), _ => None } }
|
|
1342
|
+
pub fn item_at(items: Value, position: Value, dflt: Option<Value>) -> Value {
|
|
1343
|
+
let pos = match &position { Int(n) => n.clone(), _ => kind_mismatch(format!("A position in a list is a whole number, not {}.", describe(&position))) };
|
|
1344
|
+
let l = match seq_items(&items) { Some(l) => l, None => type_err(format!("object of type '{}' has no len()", if matches!(items, Nothing) { "NoneType" } else { "object" })) };
|
|
1345
|
+
if pos.cmp(&big(1)) != Ordering::Less && pos.cmp(&big(l.len() as i64)) != Ordering::Greater { return l[pos.to_i64().unwrap() as usize - 1].clone(); }
|
|
1346
|
+
if let Some(d) = dflt { return d; }
|
|
1347
|
+
missing_value(format!("There is no item {}: the list has {} item{}.", pos.to_string(), l.len(), if l.len() == 1 { "" } else { "s" }))
|
|
1348
|
+
}
|
|
1349
|
+
pub fn set_item(items: Value, position: Value, value: Value) {
|
|
1350
|
+
item_at(items.clone(), position.clone(), None);
|
|
1351
|
+
if let (List(l), Int(n)) = (&items, &position) { l.borrow_mut()[n.to_i64().unwrap() as usize - 1] = value; }
|
|
1352
|
+
}
|
|
1353
|
+
pub fn map_set(m: Value, k: Value, v: Value) {
|
|
1354
|
+
match &m {
|
|
1355
|
+
Map(d) => d.borrow_mut().set(k, v),
|
|
1356
|
+
Nothing => type_err("'NoneType' object does not support item assignment".into()),
|
|
1357
|
+
List(_) => set_item(m, k, v),
|
|
1358
|
+
_ => type_err(format!("'{}' object does not support item assignment", if matches!(m, Money(_)) { "Money" } else { "object" })),
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
pub fn set_entry(c: Value, k: Value, v: Value) {
|
|
1362
|
+
match &c {
|
|
1363
|
+
List(_) => set_item(c, k, v),
|
|
1364
|
+
Map(d) => d.borrow_mut().set(k, v),
|
|
1365
|
+
Nothing => missing_value(format!("This value is nothing, so it has no entry for {}.", show_s(&k))),
|
|
1366
|
+
_ => kind_mismatch(format!("{} has no entries that can be changed.", describe(&c))),
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
pub fn entry(c: Value, k: Value, dflt: Option<Value>) -> Value {
|
|
1370
|
+
match &c {
|
|
1371
|
+
List(_) | Tuple(_) => item_at(c, k, dflt),
|
|
1372
|
+
Map(d) => { let d = d.borrow(); if d.has(&k) { return d.get(&k).unwrap(); } if let Some(x) = dflt { return x; } missing_value(format!("There is no entry for {}.", show_s(&k))) }
|
|
1373
|
+
Nothing => missing_value(format!("This value is nothing, so it has no entry for {}.", show_s(&k))),
|
|
1374
|
+
_ => kind_mismatch(format!("{} has no entries.", describe(&c))),
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
pub fn map_get(m: Value, k: Value, dflt: Option<Value>) -> Value {
|
|
1378
|
+
if let Map(d) = &m { let d = d.borrow(); if d.has(&k) { return d.get(&k).unwrap(); } if let Some(x) = dflt { return x; } let mut e = py_err("KeyError", py_str_s(&k)); e.arg = Some(show_s(&k)); raise(e) }
|
|
1379
|
+
if matches!(m, Nothing) { if dflt.is_some() { raise(attr_err(&m, "get")) } type_err("'NoneType' object is not subscriptable".into()) }
|
|
1380
|
+
if dflt.is_some() { raise(attr_err(&m, "get")) }
|
|
1381
|
+
if let (List(l), Int(n)) = (&m, &k) {
|
|
1382
|
+
let l = l.borrow();
|
|
1383
|
+
let len = l.len() as i64;
|
|
1384
|
+
if let Some(i) = n.to_i64() { if i >= -len && i < len { return l[(if i < 0 { len + i } else { i }) as usize].clone(); } }
|
|
1385
|
+
raise(py_err("IndexError", "list index out of range".into()))
|
|
1386
|
+
}
|
|
1387
|
+
if matches!(m, List(_)) { raise(py_err("IndexError", "list index out of range".into())) }
|
|
1388
|
+
type_err(format!("'{}' object is not subscriptable", if matches!(m, Money(_)) { "Money" } else { "object" }))
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
pub fn add_to(target: Value, value: Value) -> Value { if let List(l) = &target { l.borrow_mut().push(value); return target; } add(target, value) }
|
|
1392
|
+
pub fn append_to(target: Value, value: Value) { if let List(l) = &target { l.borrow_mut().push(value); } else { raise(attr_err(&target, "append")) } }
|
|
1393
|
+
pub fn remove_from(target: Value, value: Value) {
|
|
1394
|
+
if let Map(d) = &target { if !d.borrow().has(&value) { missing_value(format!("There is no entry for {} to remove.", show_s(&value))) } d.borrow_mut().delete(&value); return; }
|
|
1395
|
+
if !contains_v(&target, &value) { missing_value(format!("{} is not in the list, so it can't be removed.", show_s(&value))) }
|
|
1396
|
+
if let List(l) = &target {
|
|
1397
|
+
let idx = l.borrow().iter().position(|x| same(x, &value) || eq_v(x, &value));
|
|
1398
|
+
if let Some(i) = idx { l.borrow_mut().remove(i); }
|
|
1399
|
+
} else { raise(attr_err(&target, "remove")) }
|
|
1400
|
+
}
|
|
1401
|
+
pub fn sort_in_place(target: Value, key: Option<Box<dyn Fn(Value) -> Value>>, desc: bool) {
|
|
1402
|
+
if let List(l) = &target { let items = l.borrow().clone(); let sorted = py_sort_with(items, key.as_deref(), desc); *l.borrow_mut() = sorted; }
|
|
1403
|
+
else { raise(attr_err(&target, "sort")) }
|
|
1404
|
+
}
|
|
1405
|
+
pub fn reverse_in_place(target: Value) { if let List(l) = &target { l.borrow_mut().reverse(); } else { raise(attr_err(&target, "reverse")) } }
|
|
1406
|
+
|
|
1407
|
+
fn total_of(items: Vec<Value>) -> Value {
|
|
1408
|
+
if items.is_empty() { return int_n(0); }
|
|
1409
|
+
let mut it = items.into_iter();
|
|
1410
|
+
let mut result = it.next().unwrap();
|
|
1411
|
+
for x in it { result = add(result, x); }
|
|
1412
|
+
result
|
|
1413
|
+
}
|
|
1414
|
+
fn text_of(v: &Value, what: &str) -> String { if let Text(s) = v { s.to_string() } else { kind_mismatch(format!("{} needs text, but it is {}.", what, describe(v))) } }
|
|
1415
|
+
const PUNCT: &str = ".,;:!?\"'()[]{}<>“”‘’…-";
|
|
1416
|
+
fn strip_punct(w: &str) -> String { w.trim_matches(|c| PUNCT.contains(c)).to_string() }
|
|
1417
|
+
|
|
1418
|
+
/// The operations written as words: the sum of, the first of, the words of, …
|
|
1419
|
+
pub fn apply_op(op: &str, a: Value) -> Value {
|
|
1420
|
+
match op {
|
|
1421
|
+
"sum" => total_of(py_iter(a)),
|
|
1422
|
+
"average" => { let items = py_iter(a); if items.is_empty() { missing_value("I can't take the average of an empty list.".into()) } let n = items.len() as i64; divide(total_of(items), int_n(n)) }
|
|
1423
|
+
"count" | "length" => py_len(&a),
|
|
1424
|
+
"min" => { let items = py_iter(a); if items.is_empty() { missing_value("An empty list has no smallest item.".into()) } let mut best = items[0].clone(); for x in items.into_iter().skip(1) { if compare_v("<", &x, &best) { best = x; } } best }
|
|
1425
|
+
"max" => { let items = py_iter(a); if items.is_empty() { missing_value("An empty list has no largest item.".into()) } let mut best = items[0].clone(); for x in items.into_iter().skip(1) { if compare_v(">", &x, &best) { best = x; } } best }
|
|
1426
|
+
"first" => { let items = py_iter(a); if items.is_empty() { missing_value("An empty list has no first item.".into()) } items[0].clone() }
|
|
1427
|
+
"last" => { let items = py_iter(a); if items.is_empty() { missing_value("An empty list has no last item.".into()) } items[items.len() - 1].clone() }
|
|
1428
|
+
"words" => list(py_split(&py_str_s(&a)).iter().map(|p| strip_punct(p)).filter(|p| !p.is_empty()).map(string).collect()),
|
|
1429
|
+
"lines" => list(split_lines(&str_method(&a, "splitlines"))),
|
|
1430
|
+
"lowercase" => string(str_method(&a, "lower").to_lowercase()),
|
|
1431
|
+
"uppercase" => string(str_method(&a, "upper").to_uppercase()),
|
|
1432
|
+
"trimmed" => string(py_strip(&str_method(&a, "strip"))),
|
|
1433
|
+
"parts" => list(py_split(&text_of(&a, "\"the parts of\"")).into_iter().map(string).collect()),
|
|
1434
|
+
"abs" => match &a {
|
|
1435
|
+
Money(m) => Money(m.abs()),
|
|
1436
|
+
Int(n) => Int(n.abs()),
|
|
1437
|
+
Dec(d) => Dec(d.abs()),
|
|
1438
|
+
_ => kind_mismatch(format!("\"the absolute value of\" needs a number or money, but it is {}.", describe(&a))),
|
|
1439
|
+
},
|
|
1440
|
+
"jsonText" => string(json_text(&a)),
|
|
1441
|
+
"jsonData" => json_parse(&text_of(&a, "\"the JSON data in\"")),
|
|
1442
|
+
"keys" => if let Map(d) = &a { list(d.borrow().keys()) } else { raise(attr_err(&a, "keys")) },
|
|
1443
|
+
"values" => if let Map(d) = &a { list(d.borrow().values()) } else { raise(attr_err(&a, "values")) },
|
|
1444
|
+
_ => raise(py_err("NameError", format!("name '{}' is not defined", op))),
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
/// "starts with" / "ends with": both sides must be text.
|
|
1449
|
+
pub fn affix(t: Value, a: Value, end: bool) -> Value {
|
|
1450
|
+
let what = if end { "\"ends with\"" } else { "\"starts with\"" };
|
|
1451
|
+
let (x, y) = (text_of(&t, what), text_of(&a, what));
|
|
1452
|
+
Bool(if end { x.ends_with(&y) } else { x.starts_with(&y) })
|
|
1453
|
+
}
|
|
1454
|
+
/// a <= v <= hi, the way Python chains it: hi is worked out only when the first part holds.
|
|
1455
|
+
pub fn between(lo: Value, v: Value, hi: impl FnOnce() -> Value) -> Value {
|
|
1456
|
+
if !compare_v("<=", &lo, &v) { return Bool(false); }
|
|
1457
|
+
let h = hi();
|
|
1458
|
+
Bool(compare_v("<=", &v, &h))
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
pub fn joined(items: Value, sep: Value) -> Value {
|
|
1462
|
+
let sep = text_of(&sep, "\"joined with\"");
|
|
1463
|
+
let mut out = Vec::new();
|
|
1464
|
+
for (i, x) in py_iter(items).into_iter().enumerate() {
|
|
1465
|
+
if let Text(s) = &x { out.push(s.to_string()); } else { kind_mismatch(format!("\"joined with\" joins text, but item {} is {}. Turn it into text first.", i + 1, describe(&x))) }
|
|
1466
|
+
}
|
|
1467
|
+
string(out.join(&sep))
|
|
1468
|
+
}
|
|
1469
|
+
pub fn split_at(t: Value, sep: Value) -> Value {
|
|
1470
|
+
let sep = text_of(&sep, "\"split at\"");
|
|
1471
|
+
if sep.is_empty() { kind_mismatch("\"split at\" needs something to split at, not empty text.".into()) }
|
|
1472
|
+
list(text_of(&t, "\"split at\"").split(sep.as_str()).map(|p| string(p.to_string())).collect())
|
|
1473
|
+
}
|
|
1474
|
+
pub fn replacing(t: Value, old: Value, nw: Value) -> Value {
|
|
1475
|
+
let old = text_of(&old, "\"replacing\"");
|
|
1476
|
+
if old.is_empty() { kind_mismatch("\"replacing\" needs something to replace, not empty text.".into()) }
|
|
1477
|
+
let x = text_of(&t, "\"replacing\"");
|
|
1478
|
+
let parts: Vec<&str> = x.split(old.as_str()).collect();
|
|
1479
|
+
string(parts.join(&text_of(&nw, "\"replacing … with\"")))
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
pub fn read_text(path: Value) -> Value {
|
|
1483
|
+
let p = match &path { Text(s) => s.to_string(), _ => type_err(format!("expected str, bytes or os.PathLike object, not {}", if matches!(path, Nothing) { "NoneType" } else { "object" })) };
|
|
1484
|
+
match std::fs::read(&p) {
|
|
1485
|
+
Ok(bytes) => string(String::from_utf8_lossy(&bytes).to_string()),
|
|
1486
|
+
Err(e) => {
|
|
1487
|
+
if e.kind() == std::io::ErrorKind::NotFound { missing_value(format!("There is no file \"{}\" (looked in the folder the program runs in).", p)) }
|
|
1488
|
+
if std::path::Path::new(&p).is_dir() { raise(py_err("IsADirectoryError", format!("EISDIR: illegal operation on a directory, read"))) }
|
|
1489
|
+
raise(py_err("OSError", e.to_string()))
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
// ── Conversions ────────────────────────────────────────────────────────────────────────────────────────────────
|
|
1495
|
+
|
|
1496
|
+
fn number_text(s: &str) -> bool {
|
|
1497
|
+
let b = s.as_bytes();
|
|
1498
|
+
let mut i = 0;
|
|
1499
|
+
if i < b.len() && (b[i] == b'+' || b[i] == b'-') { i += 1; }
|
|
1500
|
+
if i >= b.len() || !b[i].is_ascii_digit() { return false; }
|
|
1501
|
+
while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'_') { i += 1; }
|
|
1502
|
+
if i < b.len() && b[i] == b'.' { i += 1; let d0 = i; while i < b.len() && b[i].is_ascii_digit() { i += 1; } if d0 == i { return false; } }
|
|
1503
|
+
i == b.len()
|
|
1504
|
+
}
|
|
1505
|
+
pub fn to_number(x: Value) -> Value {
|
|
1506
|
+
if is_number(&x) { return x; }
|
|
1507
|
+
if let Money(a) = &x { return Dec(a.clone()); }
|
|
1508
|
+
if let Text(t) = &x {
|
|
1509
|
+
let s = py_strip(t).replace(',', "");
|
|
1510
|
+
if number_text(&s) { return if s.contains('.') { Dec(Dec::parse(&s).unwrap()) } else { Int(BigInt::parse(&s.replace('_', "")).unwrap()) }; }
|
|
1511
|
+
}
|
|
1512
|
+
conversion_failed(format!("{} is not a number.", describe(&x)))
|
|
1513
|
+
}
|
|
1514
|
+
pub fn to_whole(x: Value) -> Value {
|
|
1515
|
+
let n = to_number(x);
|
|
1516
|
+
if is_int(&n) { return n; }
|
|
1517
|
+
if let Dec(d) = &n { if d.is_integral() { return Int(d.to_bigint()); } }
|
|
1518
|
+
conversion_failed(format!("{} is not a whole number.", show_s(&n)))
|
|
1519
|
+
}
|
|
1520
|
+
pub fn to_money(x: Value) -> Value {
|
|
1521
|
+
if matches!(x, Money(_)) { return x; }
|
|
1522
|
+
if let Text(t) = &x {
|
|
1523
|
+
let mut s = py_strip(t).replace(',', "");
|
|
1524
|
+
let negative = s.starts_with('-');
|
|
1525
|
+
s = s.trim_start_matches('-').trim_start_matches('$').to_string();
|
|
1526
|
+
if number_text(&s) { return money_of(&string(format!("{}{}", if negative { "-" } else { "" }, s))); }
|
|
1527
|
+
conversion_failed(format!("{} is not an amount of money.", describe(&x)))
|
|
1528
|
+
}
|
|
1529
|
+
Money(to_dec(&to_number(x)))
|
|
1530
|
+
}
|
|
1531
|
+
pub fn to_yes_no(x: Value) -> Value {
|
|
1532
|
+
if let Bool(_) = x { return x; }
|
|
1533
|
+
if let Text(t) = &x { let s = py_strip(t).to_lowercase(); if s == "yes" || s == "true" { return Bool(true); } if s == "no" || s == "false" { return Bool(false); } }
|
|
1534
|
+
conversion_failed(format!("{} is not yes or no.", describe(&x)))
|
|
1535
|
+
}
|
|
1536
|
+
pub fn to_date(x: Value) -> Value {
|
|
1537
|
+
if let Date(..) = x { return x; }
|
|
1538
|
+
if let Some(d) = parse_date(&py_strip(&py_str_s(&x))) { return d; }
|
|
1539
|
+
conversion_failed(format!("{} is not a date (write it as YYYY-MM-DD).", describe(&x)))
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
// ── Expect ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
1543
|
+
|
|
1544
|
+
pub fn expect_true(v: Value, t: &str) { if !matches!(v, Bool(true)) { expectation_failed(format!("{}, but it was not true.", t)) } }
|
|
1545
|
+
pub fn expect_failure(body: impl FnOnce(), t: &str, msg: Value) {
|
|
1546
|
+
match catch(body) {
|
|
1547
|
+
Ok(()) => expectation_failed(format!("{}, but it did not fail.", t)),
|
|
1548
|
+
Err(err) => {
|
|
1549
|
+
if err.thunder() && !matches!(msg, Nothing) {
|
|
1550
|
+
let m = match &msg { Text(s) => s.to_string(), _ => type_err(format!("'in <string>' requires string as left operand, not {}", if is_int(&msg) { "int" } else { "object" })) };
|
|
1551
|
+
if !err.message.contains(&m) { expectation_failed(format!("{}, but it failed with \"{}\".", t, err.message)) }
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
fn check(name: &str, a: &Value, b: &Value) -> bool {
|
|
1557
|
+
match name {
|
|
1558
|
+
"is" => eq_v(a, b),
|
|
1559
|
+
"is not" => !eq_v(a, b),
|
|
1560
|
+
"at least" => compare_v(">=", a, b),
|
|
1561
|
+
"at most" => compare_v("<=", a, b),
|
|
1562
|
+
"more than" => compare_v(">", a, b),
|
|
1563
|
+
"less than" => compare_v("<", a, b),
|
|
1564
|
+
"nothing" => matches!(a, Nothing),
|
|
1565
|
+
"not nothing" => !matches!(a, Nothing),
|
|
1566
|
+
"empty" => eq_v(&py_len(a), &int_n(0)),
|
|
1567
|
+
"positive" => compare_v(">", a, &int_n(0)),
|
|
1568
|
+
"negative" => compare_v("<", a, &int_n(0)),
|
|
1569
|
+
"zero" => eq_v(a, &int_n(0)),
|
|
1570
|
+
"between" => { let (lo, hi) = match b { List(l) => { let l = l.borrow(); (l[0].clone(), l[1].clone()) } _ => (Nothing, Nothing) }; compare_v("<=", &lo, a) && compare_v("<=", a, &hi) }
|
|
1571
|
+
"in" => contains_v(b, a),
|
|
1572
|
+
"contains" => contains_v(a, b),
|
|
1573
|
+
_ => false,
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
fn known_check(name: &str) -> bool { matches!(name, "is" | "is not" | "at least" | "at most" | "more than" | "less than" | "nothing" | "not nothing" | "empty" | "positive" | "negative" | "zero" | "between" | "in" | "contains") }
|
|
1577
|
+
pub fn expect_value(actual: Value, full: &str, op: &str, want: Value, t: &str) {
|
|
1578
|
+
let ok = if known_check(full) { check(full, &actual, &want) } else { !check(op, &actual, &want) };
|
|
1579
|
+
if !ok { expectation_failed(format!("{}, but it was {}.", t, show_s(&actual))) }
|
|
1580
|
+
}
|
|
1581
|
+
|
|
1582
|
+
/// "If this fails": the error, in words.
|
|
1583
|
+
pub fn explain(e: TErr) -> Value { string(explain_err(&e)) }
|
|
1584
|
+
|
|
1585
|
+
// ── Running the program or its tests ───────────────────────────────────────────────────────────────────────────
|
|
1586
|
+
|
|
1587
|
+
fn report(e: &TErr) {
|
|
1588
|
+
flush();
|
|
1589
|
+
eprintln!("{}", describe_error(e));
|
|
1590
|
+
EXIT.with(|x| *x.borrow_mut() = 1);
|
|
1591
|
+
ABORTED.with(|a| *a.borrow_mut() = true);
|
|
1592
|
+
}
|
|
1593
|
+
fn aborted() -> bool { ABORTED.with(|a| *a.borrow()) }
|
|
1594
|
+
|
|
1595
|
+
/// Work out a file's kept values; an error stops the program with a Thunder message.
|
|
1596
|
+
pub fn init(file: &'static str, body: impl FnOnce()) {
|
|
1597
|
+
if aborted() { return; }
|
|
1598
|
+
if let Err(e) = catch(|| frame(file, 0, body)) { report(&e); }
|
|
1599
|
+
}
|
|
1600
|
+
pub fn run(main: impl FnOnce()) {
|
|
1601
|
+
if aborted() { return; }
|
|
1602
|
+
if let Err(e) = catch(main) { report(&e); }
|
|
1603
|
+
}
|
|
1604
|
+
/// Every Test block, the way run_tests.py runs them: one line per test, then the totals.
|
|
1605
|
+
pub fn run_tests(modules: Vec<(&'static str, Vec<(&'static str, fn(), i64)>)>) {
|
|
1606
|
+
if aborted() { return; }
|
|
1607
|
+
let (mut passed, mut failed) = (0, 0);
|
|
1608
|
+
for (file, tests) in modules {
|
|
1609
|
+
for (title, f, line) in tests {
|
|
1610
|
+
match catch(f) {
|
|
1611
|
+
Ok(()) => { passed += 1; say(string(format!("PASS {} ({}, line {})", title, file, line))); }
|
|
1612
|
+
Err(e) => { failed += 1; say(string(format!("FAIL {} ({}, line {})", title, file, line))); say(string(format!(" {}", describe_error(&e)))); }
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
let total = passed + failed;
|
|
1617
|
+
say(string(format!("{} test{}: {} passed, {} failed", total, if total == 1 { "" } else { "s" }, passed, failed)));
|
|
1618
|
+
if failed > 0 { EXIT.with(|x| *x.borrow_mut() = 1); }
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
/// The program's entry: on a thread with a deep stack (Thunder allows calls nested about 1000 deep), with Rust's own
|
|
1622
|
+
/// panic messages silenced (a Thunder error is reported in Thunder words instead). `body(tests)` runs the program
|
|
1623
|
+
/// (tests = false) or its Test blocks (tests = true, from `--tests` on the command line).
|
|
1624
|
+
pub fn start(body: fn(bool)) {
|
|
1625
|
+
std::panic::set_hook(Box::new(|_| {}));
|
|
1626
|
+
let tests = std::env::args().any(|a| a == "--tests");
|
|
1627
|
+
let handle = std::thread::Builder::new().stack_size(1 << 30).spawn(move || {
|
|
1628
|
+
body(tests);
|
|
1629
|
+
flush();
|
|
1630
|
+
EXIT.with(|x| *x.borrow())
|
|
1631
|
+
}).expect("start the Thunder thread");
|
|
1632
|
+
let code = handle.join().unwrap_or(70);
|
|
1633
|
+
std::process::exit(code);
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
/// A kind for records, made once per program run.
|
|
1637
|
+
pub fn kind(py: &'static str, fields: Vec<(&'static str, &'static str)>, rules: Vec<(&'static str, Vec<Rule>)>) -> Rc<Kind> { Rc::new(Kind { py, fields, rules }) }
|
|
1638
|
+
|
|
1639
|
+
/// A kept value's slot: written once by init, read anywhere.
|
|
1640
|
+
pub struct Kept(RefCell<Value>);
|
|
1641
|
+
impl Kept {
|
|
1642
|
+
pub const fn new() -> Kept { Kept(RefCell::new(Value::Nothing)) }
|
|
1643
|
+
pub fn get(&self) -> Value { self.0.borrow().clone() }
|
|
1644
|
+
pub fn set(&self, v: Value) { *self.0.borrow_mut() = v; }
|
|
1645
|
+
}
|