@skillstech/thunderlang 1.0.3 → 1.1.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 +207 -0
- package/dist/core.cjs +13779 -10043
- package/dist/index.cjs +28500 -24392
- package/dist/learn.cjs +12853 -9579
- package/intent-graph.schema.json +11 -0
- package/package.json +6 -2
- package/src/cli.mjs +141 -58
- package/src/codegen.mjs +145 -55
- package/src/conformance.mjs +15 -6
- package/src/core/check.mjs +725 -0
- package/src/core/cli.mjs +133 -0
- package/src/core/diagnostics.mjs +81 -0
- package/src/core/format.mjs +20 -0
- package/src/core/from-python.mjs +645 -0
- package/src/core/index.mjs +38 -0
- package/src/core/lexer.mjs +115 -0
- package/src/core/parser.mjs +742 -0
- package/src/core/project.mjs +167 -0
- package/src/core/round-trip.mjs +150 -0
- package/src/core/runtime-python.mjs +801 -0
- package/src/core/target-python.mjs +486 -0
- package/src/core.d.ts +5 -2
- package/src/core.mjs +5 -2
- package/src/data-schema.mjs +8 -1
- package/src/emit.mjs +1 -1
- package/src/evidence.mjs +1 -1
- package/src/expr.mjs +81 -4
- package/src/form-words.mjs +2 -0
- package/src/index.d.ts +8 -1
- package/src/index.mjs +5 -1
- package/src/intent-schema.mjs +1 -0
- package/src/libraries.mjs +2 -2
- package/src/mcp.mjs +23 -0
- package/src/meaning.mjs +47 -7
- package/src/model.d.mts +7 -3
- package/src/model.mjs +30 -9
- package/src/money.d.mts +18 -0
- package/src/money.mjs +124 -0
- package/src/plain-contract.mjs +18 -2
- package/src/powershell.mjs +24 -5
- package/src/read-repo.mjs +1 -0
- package/src/read.d.mts +11 -0
- package/src/read.mjs +121 -13
- package/src/review-comment.d.mts +16 -0
- package/src/review-comment.mjs +145 -0
- package/src/rlang.mjs +10 -3
- package/src/say-less.mjs +1432 -0
- package/src/shell.mjs +45 -8
- package/src/sql-proc.mjs +1198 -0
- package/src/sql.mjs +87 -119
- package/src/steps.mjs +188 -37
- package/src/system.mjs +153 -44
- package/src/target-cs.mjs +39 -34
- package/src/target-elixir.mjs +40 -30
- package/src/target-go.mjs +41 -36
- package/src/target-java.mjs +34 -27
- package/src/target-kotlin.mjs +43 -35
- package/src/target-py.mjs +57 -55
- package/src/target-result.d.mts +48 -0
- package/src/target-result.mjs +112 -0
- package/src/target-rust.mjs +42 -38
- package/src/target-scala.mjs +45 -35
- package/src/target-ts.mjs +37 -45
- package/src/target-types.mjs +41 -5
- package/src/target-util.mjs +55 -2
- package/src/trace-cli.mjs +58 -0
- package/src/trace-fs.mjs +76 -0
- package/src/trace.mjs +261 -0
- package/src/translate.d.mts +3 -0
- package/src/translate.mjs +62 -32
- package/src/why-cli.mjs +31 -0
- package/src/why.d.mts +28 -0
- package/src/why.mjs +532 -0
- package/src/write-steps.mjs +22 -5
|
@@ -0,0 +1,801 @@
|
|
|
1
|
+
// thunder_runtime.py: written next to every generated Python program. It is plain Python (3.10+, standard
|
|
2
|
+
// library only), so the generated program runs without Thunder installed. Each function implements one rule
|
|
3
|
+
// from the "Semantics" section of docs/core.md; change both together.
|
|
4
|
+
|
|
5
|
+
export const RUNTIME_VERSION = '0.1.0';
|
|
6
|
+
|
|
7
|
+
export const PYTHON_RUNTIME = String.raw`"""Thunder runtime for generated Python (Thunder Core v0, runtime 0.1.0).
|
|
8
|
+
|
|
9
|
+
Written by the Thunder compiler next to the code it generates. Standard library only.
|
|
10
|
+
The rules implemented here are the Thunder semantics that must be the same in every target language:
|
|
11
|
+
exact decimals, money, division, rounding, positions that start at 1, "nothing", and errors that name
|
|
12
|
+
the Thunder line (read from the "# thunder:N" comments in the generated files).
|
|
13
|
+
"""
|
|
14
|
+
import json
|
|
15
|
+
import linecache
|
|
16
|
+
import re
|
|
17
|
+
import sys
|
|
18
|
+
import traceback
|
|
19
|
+
from contextlib import contextmanager
|
|
20
|
+
from dataclasses import fields, is_dataclass
|
|
21
|
+
from datetime import date
|
|
22
|
+
from decimal import ROUND_HALF_UP, Decimal, DivisionByZero, InvalidOperation
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ThunderError(Exception):
|
|
26
|
+
"""An error with a plain-words message. code is the stable Thunder code (TC5xx)."""
|
|
27
|
+
|
|
28
|
+
code = "TC500"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Stop(ThunderError):
|
|
32
|
+
code = "TC507"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class RuleBroken(ThunderError):
|
|
36
|
+
code = "TC504"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ExpectationFailed(ThunderError):
|
|
40
|
+
code = "TC505"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class KindMismatch(ThunderError, TypeError):
|
|
44
|
+
code = "TC506"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ConversionFailed(ThunderError, ValueError):
|
|
48
|
+
code = "TC509"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class MissingValue(ThunderError, LookupError):
|
|
52
|
+
code = "TC503"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class DividedByZero(ThunderError, ZeroDivisionError):
|
|
56
|
+
code = "TC501"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# ---------------------------------------------------------------- numbers and money
|
|
60
|
+
|
|
61
|
+
def _is_number(x):
|
|
62
|
+
return isinstance(x, (int, Decimal)) and not isinstance(x, bool)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class _NotGiven:
|
|
66
|
+
def __repr__(self):
|
|
67
|
+
return "not given"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
NOT_GIVEN = _NotGiven()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def num(x):
|
|
74
|
+
"""A Python float that reaches Thunder becomes the exact decimal it is written as (19.99, never
|
|
75
|
+
19.989999999999998). Everything else is left as it is, so text, lists and records pass through."""
|
|
76
|
+
if isinstance(x, float) and not isinstance(x, bool):
|
|
77
|
+
return Decimal(repr(x))
|
|
78
|
+
return x
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _decimal(x):
|
|
82
|
+
if isinstance(x, Decimal):
|
|
83
|
+
return x
|
|
84
|
+
if isinstance(x, bool):
|
|
85
|
+
raise KindMismatch("A yes/no value was used where a number was needed.")
|
|
86
|
+
if isinstance(x, int):
|
|
87
|
+
return Decimal(x)
|
|
88
|
+
if isinstance(x, float):
|
|
89
|
+
return Decimal(repr(x))
|
|
90
|
+
if x is None:
|
|
91
|
+
raise KindMismatch("A value was nothing where a number was needed.")
|
|
92
|
+
raise KindMismatch("%s was used where a number was needed." % _describe(x))
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class Money:
|
|
96
|
+
"""An exact amount of money. Money adds to money; it multiplies and divides by plain numbers."""
|
|
97
|
+
|
|
98
|
+
__slots__ = ("amount",)
|
|
99
|
+
|
|
100
|
+
def __init__(self, amount):
|
|
101
|
+
if isinstance(amount, Money):
|
|
102
|
+
amount = amount.amount
|
|
103
|
+
elif isinstance(amount, str):
|
|
104
|
+
amount = Decimal(amount.replace(",", "").replace("$", "").strip())
|
|
105
|
+
else:
|
|
106
|
+
amount = _decimal(amount)
|
|
107
|
+
object.__setattr__(self, "amount", amount)
|
|
108
|
+
|
|
109
|
+
def __setattr__(self, name, value):
|
|
110
|
+
raise AttributeError("Money cannot be changed; make new money instead.")
|
|
111
|
+
|
|
112
|
+
def _other(self, other, verb):
|
|
113
|
+
if isinstance(other, Money):
|
|
114
|
+
return other.amount
|
|
115
|
+
if other == 0 and _is_number(other):
|
|
116
|
+
return Decimal(0)
|
|
117
|
+
raise KindMismatch("I can't %s money and %s. Write the number as money, for example $5." % (verb, _describe(other)))
|
|
118
|
+
|
|
119
|
+
def __add__(self, other):
|
|
120
|
+
return Money(self.amount + self._other(other, "add"))
|
|
121
|
+
|
|
122
|
+
__radd__ = __add__
|
|
123
|
+
|
|
124
|
+
def __sub__(self, other):
|
|
125
|
+
return Money(self.amount - self._other(other, "subtract"))
|
|
126
|
+
|
|
127
|
+
def __rsub__(self, other):
|
|
128
|
+
return Money(self._other(other, "subtract") - self.amount)
|
|
129
|
+
|
|
130
|
+
def __mul__(self, other):
|
|
131
|
+
if isinstance(other, Money):
|
|
132
|
+
raise KindMismatch("Money can't be multiplied by money.")
|
|
133
|
+
return Money(self.amount * _decimal(other))
|
|
134
|
+
|
|
135
|
+
__rmul__ = __mul__
|
|
136
|
+
|
|
137
|
+
def __truediv__(self, other):
|
|
138
|
+
return divide(self, other)
|
|
139
|
+
|
|
140
|
+
def __neg__(self):
|
|
141
|
+
return Money(-self.amount)
|
|
142
|
+
|
|
143
|
+
def __abs__(self):
|
|
144
|
+
return Money(abs(self.amount))
|
|
145
|
+
|
|
146
|
+
def _cmp(self, other):
|
|
147
|
+
if other is None:
|
|
148
|
+
return None
|
|
149
|
+
return self._other(other, "compare")
|
|
150
|
+
|
|
151
|
+
def __eq__(self, other):
|
|
152
|
+
if other is None or isinstance(other, (str, bool)):
|
|
153
|
+
return False
|
|
154
|
+
return self.amount == self._cmp(other)
|
|
155
|
+
|
|
156
|
+
def __ne__(self, other):
|
|
157
|
+
return not self.__eq__(other)
|
|
158
|
+
|
|
159
|
+
def __lt__(self, other):
|
|
160
|
+
return self.amount < self._cmp(other)
|
|
161
|
+
|
|
162
|
+
def __le__(self, other):
|
|
163
|
+
return self.amount <= self._cmp(other)
|
|
164
|
+
|
|
165
|
+
def __gt__(self, other):
|
|
166
|
+
return self.amount > self._cmp(other)
|
|
167
|
+
|
|
168
|
+
def __ge__(self, other):
|
|
169
|
+
return self.amount >= self._cmp(other)
|
|
170
|
+
|
|
171
|
+
def __hash__(self):
|
|
172
|
+
return hash(("Money", self.amount))
|
|
173
|
+
|
|
174
|
+
def __str__(self):
|
|
175
|
+
a = self.amount
|
|
176
|
+
places = max(2, -a.as_tuple().exponent) if a.as_tuple().exponent < 0 else 2
|
|
177
|
+
text = format(abs(a), ",.%df" % places)
|
|
178
|
+
return ("-$" if a < 0 else "$") + text
|
|
179
|
+
|
|
180
|
+
def __repr__(self):
|
|
181
|
+
return "Money(%r)" % format(self.amount, "f")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def divide(a, b):
|
|
185
|
+
"""Division always gives the exact answer as a decimal: 7 / 2 is 3.5, never 3."""
|
|
186
|
+
if isinstance(a, Money):
|
|
187
|
+
if isinstance(b, Money):
|
|
188
|
+
if b.amount == 0:
|
|
189
|
+
raise DividedByZero("You divided by zero.")
|
|
190
|
+
return a.amount / b.amount
|
|
191
|
+
d = _decimal(b)
|
|
192
|
+
if d == 0:
|
|
193
|
+
raise DividedByZero("You divided by zero.")
|
|
194
|
+
return Money(a.amount / d)
|
|
195
|
+
if isinstance(b, Money):
|
|
196
|
+
raise KindMismatch("A plain number can't be divided by money.")
|
|
197
|
+
x, y = _decimal(a), _decimal(b)
|
|
198
|
+
if y == 0:
|
|
199
|
+
raise DividedByZero("You divided by zero.")
|
|
200
|
+
return x / y
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def modulo(a, b):
|
|
204
|
+
"""The remainder after dividing, with the sign of the divisor (7 mod 3 is 1, -7 mod 3 is 2)."""
|
|
205
|
+
money = isinstance(a, Money)
|
|
206
|
+
x = a.amount if money else _decimal(a)
|
|
207
|
+
y = b.amount if isinstance(b, Money) else _decimal(b)
|
|
208
|
+
if y == 0:
|
|
209
|
+
raise DividedByZero("You divided by zero.")
|
|
210
|
+
r = x % y
|
|
211
|
+
if r != 0 and (r < 0) != (y < 0):
|
|
212
|
+
r += y
|
|
213
|
+
if money:
|
|
214
|
+
return Money(r)
|
|
215
|
+
return int(r) if isinstance(a, int) and isinstance(b, int) else r
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def round_to(x, places=0):
|
|
219
|
+
"""Rounds half away from zero (2.5 -> 3, -2.5 -> -3), the way people round by hand."""
|
|
220
|
+
if isinstance(x, Money):
|
|
221
|
+
return Money(x.amount.quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP))
|
|
222
|
+
if isinstance(x, int) and not isinstance(x, bool):
|
|
223
|
+
return x
|
|
224
|
+
d = _decimal(x).quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
|
|
225
|
+
return int(d) if places == 0 else d
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
# ---------------------------------------------------------------- showing values
|
|
229
|
+
|
|
230
|
+
def show(v):
|
|
231
|
+
"""A value the way Thunder says it: yes/no, nothing, $1.50, 3.5 (no trailing zeros), [1, 2]."""
|
|
232
|
+
if v is None:
|
|
233
|
+
return "nothing"
|
|
234
|
+
if v is True:
|
|
235
|
+
return "yes"
|
|
236
|
+
if v is False:
|
|
237
|
+
return "no"
|
|
238
|
+
if isinstance(v, Decimal):
|
|
239
|
+
text = format(v, "f")
|
|
240
|
+
return text.rstrip("0").rstrip(".") if "." in text else text
|
|
241
|
+
if isinstance(v, (list, tuple)):
|
|
242
|
+
return "[" + ", ".join(show(x) for x in v) + "]"
|
|
243
|
+
if isinstance(v, dict):
|
|
244
|
+
return "{" + ", ".join("%s: %s" % (show(k), show(x)) for k, x in v.items()) + "}"
|
|
245
|
+
if is_dataclass(v) and not isinstance(v, type):
|
|
246
|
+
return "%s(%s)" % (type(v).__name__, ", ".join("%s: %s" % (f.name.replace("_", " "), show(getattr(v, f.name))) for f in fields(v)))
|
|
247
|
+
if isinstance(v, date):
|
|
248
|
+
return v.isoformat()
|
|
249
|
+
return str(v)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def yes_no(v):
|
|
253
|
+
"""A condition or a comparison with yes/no needs a real yes/no value: "truthy" differs between languages."""
|
|
254
|
+
if isinstance(v, bool):
|
|
255
|
+
return v
|
|
256
|
+
raise KindMismatch("This needs a yes/no value, but it is %s. Compare it instead, for example: is 0, is empty, is nothing." % _describe(v))
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _describe(v):
|
|
260
|
+
if v is None:
|
|
261
|
+
return "nothing"
|
|
262
|
+
if isinstance(v, bool):
|
|
263
|
+
return "a yes/no value"
|
|
264
|
+
if isinstance(v, str):
|
|
265
|
+
return 'the text "%s"' % v
|
|
266
|
+
if _is_number(v):
|
|
267
|
+
return "the number %s" % show(v)
|
|
268
|
+
if isinstance(v, Money):
|
|
269
|
+
return str(v)
|
|
270
|
+
return "a value (%s)" % type(v).__name__
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
# ---------------------------------------------------------------- conversions
|
|
274
|
+
|
|
275
|
+
_NUMBER = re.compile(r"^[+-]?(\d[\d_]*)(\.\d+)?$")
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def to_number(x):
|
|
279
|
+
if _is_number(x):
|
|
280
|
+
return x
|
|
281
|
+
if isinstance(x, Money):
|
|
282
|
+
return x.amount
|
|
283
|
+
if isinstance(x, float):
|
|
284
|
+
return Decimal(repr(x))
|
|
285
|
+
if isinstance(x, str):
|
|
286
|
+
s = x.strip().replace(",", "")
|
|
287
|
+
if _NUMBER.match(s):
|
|
288
|
+
return int(s.replace("_", "")) if "." not in s else Decimal(s)
|
|
289
|
+
raise ConversionFailed("%s is not a number." % _describe(x))
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def to_whole(x):
|
|
293
|
+
n = to_number(x)
|
|
294
|
+
if isinstance(n, int):
|
|
295
|
+
return n
|
|
296
|
+
if n == n.to_integral_value():
|
|
297
|
+
return int(n)
|
|
298
|
+
raise ConversionFailed("%s is not a whole number." % show(n))
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def to_money(x):
|
|
302
|
+
if isinstance(x, Money):
|
|
303
|
+
return x
|
|
304
|
+
if isinstance(x, str):
|
|
305
|
+
s = x.strip().replace(",", "")
|
|
306
|
+
neg = s.startswith("-")
|
|
307
|
+
s = s.lstrip("-").lstrip("$")
|
|
308
|
+
if _NUMBER.match(s):
|
|
309
|
+
return Money(("-" if neg else "") + s)
|
|
310
|
+
raise ConversionFailed("%s is not an amount of money." % _describe(x))
|
|
311
|
+
return Money(to_number(x))
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def to_text(x):
|
|
315
|
+
return show(x)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def to_yes_no(x):
|
|
319
|
+
if isinstance(x, bool):
|
|
320
|
+
return x
|
|
321
|
+
if isinstance(x, str) and x.strip().lower() in ("yes", "true"):
|
|
322
|
+
return True
|
|
323
|
+
if isinstance(x, str) and x.strip().lower() in ("no", "false"):
|
|
324
|
+
return False
|
|
325
|
+
raise ConversionFailed("%s is not yes or no." % _describe(x))
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def to_date(x):
|
|
329
|
+
if isinstance(x, date):
|
|
330
|
+
return x
|
|
331
|
+
try:
|
|
332
|
+
return date.fromisoformat(str(x).strip())
|
|
333
|
+
except ValueError:
|
|
334
|
+
raise ConversionFailed("%s is not a date (write it as YYYY-MM-DD)." % _describe(x)) from None
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
# ---------------------------------------------------------------- lists, maps, records
|
|
338
|
+
|
|
339
|
+
def total_of(items):
|
|
340
|
+
items = list(items)
|
|
341
|
+
if not items:
|
|
342
|
+
return 0
|
|
343
|
+
result = items[0]
|
|
344
|
+
for x in items[1:]:
|
|
345
|
+
result = result + x
|
|
346
|
+
return result
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _text(v, what):
|
|
350
|
+
if not isinstance(v, str):
|
|
351
|
+
raise KindMismatch("%s needs text, but it is %s." % (what, _describe(v)))
|
|
352
|
+
return v
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def starts_with(text, start):
|
|
356
|
+
return _text(text, '"starts with"').startswith(_text(start, '"starts with"'))
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def ends_with(text, end):
|
|
360
|
+
return _text(text, '"ends with"').endswith(_text(end, '"ends with"'))
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def joined(items, sep):
|
|
364
|
+
"""The items of a list as one text, with sep between them. Every item must be text (no silent conversion)."""
|
|
365
|
+
sep = _text(sep, '"joined with"')
|
|
366
|
+
out = []
|
|
367
|
+
for i, x in enumerate(items):
|
|
368
|
+
if not isinstance(x, str):
|
|
369
|
+
raise KindMismatch('"joined with" joins text, but item %d is %s. Turn it into text first.' % (i + 1, _describe(x)))
|
|
370
|
+
out.append(x)
|
|
371
|
+
return sep.join(out)
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def split_at(text, sep):
|
|
375
|
+
"""Text cut at each sep: "a,,b" split at "," is ["a", "", "b"] (empty parts are kept)."""
|
|
376
|
+
sep = _text(sep, '"split at"')
|
|
377
|
+
if sep == "":
|
|
378
|
+
raise KindMismatch('"split at" needs something to split at, not empty text.')
|
|
379
|
+
return _text(text, '"split at"').split(sep)
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def parts_of(text):
|
|
383
|
+
"""The parts of text between runs of spaces, tabs and new lines; no empty parts, punctuation kept."""
|
|
384
|
+
return _text(text, '"the parts of"').split()
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def replacing(text, old, new):
|
|
388
|
+
old = _text(old, '"replacing"')
|
|
389
|
+
if old == "":
|
|
390
|
+
raise KindMismatch('"replacing" needs something to replace, not empty text.')
|
|
391
|
+
return _text(text, '"replacing"').replace(old, _text(new, '"replacing … with"'))
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def sorted_values(items, descending=False):
|
|
395
|
+
return sorted([num(x) for x in items], reverse=descending) if any(isinstance(x, float) for x in items) else sorted(items, reverse=descending)
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def absolute(v):
|
|
399
|
+
if isinstance(v, Money):
|
|
400
|
+
return Money(abs(v.amount))
|
|
401
|
+
if isinstance(v, bool) or not isinstance(v, (int, float, Decimal)):
|
|
402
|
+
raise KindMismatch('"the absolute value of" needs a number or money, but it is %s.' % _describe(v))
|
|
403
|
+
return abs(num(v))
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _json_ready(v):
|
|
407
|
+
if v is None or isinstance(v, (bool, str, int)):
|
|
408
|
+
return v
|
|
409
|
+
if isinstance(v, float):
|
|
410
|
+
return Decimal(repr(v))
|
|
411
|
+
if isinstance(v, Decimal):
|
|
412
|
+
return v
|
|
413
|
+
if isinstance(v, Money):
|
|
414
|
+
raise KindMismatch("Money has no JSON form of its own: use its amount, for example price's amount.")
|
|
415
|
+
if isinstance(v, (list, tuple)):
|
|
416
|
+
return [_json_ready(x) for x in v]
|
|
417
|
+
if isinstance(v, dict):
|
|
418
|
+
out = {}
|
|
419
|
+
for k, x in v.items():
|
|
420
|
+
if not isinstance(k, str):
|
|
421
|
+
raise KindMismatch("A JSON object's keys are text, but one is %s." % _describe(k))
|
|
422
|
+
out[k] = _json_ready(x)
|
|
423
|
+
return out
|
|
424
|
+
if is_dataclass(v):
|
|
425
|
+
return {f.name: _json_ready(getattr(v, f.name)) for f in fields(v)}
|
|
426
|
+
raise KindMismatch("%s has no JSON form." % _describe(v))
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def json_text(v):
|
|
430
|
+
"""A value as JSON text, written as Python's json.dumps writes it (", " and ": "); numbers exactly."""
|
|
431
|
+
ready = _json_ready(v)
|
|
432
|
+
marker = {}
|
|
433
|
+
def default(x):
|
|
434
|
+
if isinstance(x, Decimal):
|
|
435
|
+
key = "\u0000%d\u0000" % len(marker)
|
|
436
|
+
marker[key] = format(x, "f") if x == x.to_integral_value() and "E" in str(x) else str(x)
|
|
437
|
+
return key
|
|
438
|
+
raise TypeError(x)
|
|
439
|
+
def swap(o):
|
|
440
|
+
if isinstance(o, Decimal):
|
|
441
|
+
return default(o)
|
|
442
|
+
if isinstance(o, list):
|
|
443
|
+
return [swap(x) for x in o]
|
|
444
|
+
if isinstance(o, dict):
|
|
445
|
+
return {k: swap(x) for k, x in o.items()}
|
|
446
|
+
return o
|
|
447
|
+
text = json.dumps(swap(ready))
|
|
448
|
+
for key, number in marker.items():
|
|
449
|
+
text = text.replace(json.dumps(key), number)
|
|
450
|
+
return text
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def json_data(text):
|
|
454
|
+
"""JSON text read into lists, maps, text, yes/no, nothing, and exact numbers (never binary floats)."""
|
|
455
|
+
try:
|
|
456
|
+
return json.loads(_text(text, '"the JSON data in"'), parse_float=Decimal)
|
|
457
|
+
except json.JSONDecodeError as e:
|
|
458
|
+
raise ConversionFailed("This is not JSON: %s (line %d, column %d)." % (e.msg, e.lineno, e.colno))
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def words_of(text):
|
|
462
|
+
"""The words in text: split at spaces, with punctuation at either end removed ("dog." is "dog"; "don't" stays)."""
|
|
463
|
+
words = []
|
|
464
|
+
for piece in str(text).split():
|
|
465
|
+
word = piece.strip(_PUNCTUATION)
|
|
466
|
+
if word:
|
|
467
|
+
words.append(word)
|
|
468
|
+
return words
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
_PUNCTUATION = ".,;:!?\"'()[]{}<>\u201c\u201d\u2018\u2019\u2026-"
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def average_of(items):
|
|
475
|
+
items = list(items)
|
|
476
|
+
if not items:
|
|
477
|
+
raise MissingValue("I can't take the average of an empty list.")
|
|
478
|
+
return divide(total_of(items), len(items))
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def smallest_of(items):
|
|
482
|
+
items = list(items)
|
|
483
|
+
if not items:
|
|
484
|
+
raise MissingValue("An empty list has no smallest item.")
|
|
485
|
+
return min(items)
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def largest_of(items):
|
|
489
|
+
items = list(items)
|
|
490
|
+
if not items:
|
|
491
|
+
raise MissingValue("An empty list has no largest item.")
|
|
492
|
+
return max(items)
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def first_of(items):
|
|
496
|
+
items = list(items)
|
|
497
|
+
if not items:
|
|
498
|
+
raise MissingValue("An empty list has no first item.")
|
|
499
|
+
return items[0]
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def last_of(items):
|
|
503
|
+
items = list(items)
|
|
504
|
+
if not items:
|
|
505
|
+
raise MissingValue("An empty list has no last item.")
|
|
506
|
+
return items[-1]
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def item_at(items, position, *default):
|
|
510
|
+
"""Positions start at 1: item 1 is the first item."""
|
|
511
|
+
if not isinstance(position, int) or isinstance(position, bool):
|
|
512
|
+
raise KindMismatch("A position in a list is a whole number, not %s." % _describe(position))
|
|
513
|
+
if 1 <= position <= len(items):
|
|
514
|
+
return items[position - 1]
|
|
515
|
+
if default:
|
|
516
|
+
return default[0]
|
|
517
|
+
raise MissingValue("There is no item %d: the list has %d item%s." % (position, len(items), "" if len(items) == 1 else "s"))
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def set_item(items, position, value):
|
|
521
|
+
item_at(items, position)
|
|
522
|
+
items[position - 1] = value
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def set_entry(container, key, value):
|
|
526
|
+
"""Set an entry when the kind is not known in advance: a list position (from 1) or a map key."""
|
|
527
|
+
if isinstance(container, list):
|
|
528
|
+
set_item(container, key, value)
|
|
529
|
+
elif isinstance(container, dict):
|
|
530
|
+
container[key] = value
|
|
531
|
+
elif container is None:
|
|
532
|
+
raise MissingValue("This value is nothing, so it has no entry for %s." % show(key))
|
|
533
|
+
else:
|
|
534
|
+
raise KindMismatch("%s has no entries that can be changed." % _describe(container))
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def entry(container, key, *default):
|
|
538
|
+
if isinstance(container, (list, tuple)):
|
|
539
|
+
return item_at(container, key, *default)
|
|
540
|
+
if isinstance(container, dict):
|
|
541
|
+
if key in container:
|
|
542
|
+
return container[key]
|
|
543
|
+
if default:
|
|
544
|
+
return default[0]
|
|
545
|
+
raise MissingValue("There is no entry for %s." % show(key))
|
|
546
|
+
if container is None:
|
|
547
|
+
raise MissingValue("This value is nothing, so it has no entry for %s." % show(key))
|
|
548
|
+
raise KindMismatch("%s has no entries." % _describe(container))
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def _field_names(key):
|
|
552
|
+
yield key
|
|
553
|
+
yield key.replace(" ", "_")
|
|
554
|
+
yield key.lower()
|
|
555
|
+
yield key.lower().replace(" ", "_")
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def get_field(obj, key):
|
|
559
|
+
"""A field read from a value whose kind is not known in advance (a CSV row, a value from Python)."""
|
|
560
|
+
if obj is None:
|
|
561
|
+
raise MissingValue("This value is nothing, so it has no %s." % key)
|
|
562
|
+
if isinstance(obj, dict):
|
|
563
|
+
for k in _field_names(key):
|
|
564
|
+
if k in obj:
|
|
565
|
+
return obj[k]
|
|
566
|
+
lowered = {str(k).strip().lower(): v for k, v in obj.items()}
|
|
567
|
+
if key.lower() in lowered:
|
|
568
|
+
return lowered[key.lower()]
|
|
569
|
+
raise MissingValue('There is no field "%s". Fields here: %s.' % (key, ", ".join(str(k) for k in obj)))
|
|
570
|
+
for k in _field_names(key):
|
|
571
|
+
if hasattr(obj, k):
|
|
572
|
+
return getattr(obj, k)
|
|
573
|
+
raise MissingValue('%s has no field "%s".' % (_describe(obj), key))
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def set_field(obj, key, value):
|
|
577
|
+
if isinstance(obj, dict):
|
|
578
|
+
obj[key] = value
|
|
579
|
+
return
|
|
580
|
+
for k in _field_names(key):
|
|
581
|
+
if hasattr(obj, k):
|
|
582
|
+
setattr(obj, k, value)
|
|
583
|
+
return
|
|
584
|
+
raise MissingValue('%s has no field "%s".' % (_describe(obj), key))
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
def add_to(target, value):
|
|
588
|
+
if isinstance(target, list):
|
|
589
|
+
target.append(value)
|
|
590
|
+
return target
|
|
591
|
+
return target + value
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
def remove_from(target, value):
|
|
595
|
+
if isinstance(target, dict):
|
|
596
|
+
if value not in target:
|
|
597
|
+
raise MissingValue("There is no entry for %s to remove." % show(value))
|
|
598
|
+
del target[value]
|
|
599
|
+
return
|
|
600
|
+
if value not in target:
|
|
601
|
+
raise MissingValue("%s is not in the list, so it can't be removed." % show(value))
|
|
602
|
+
target.remove(value)
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
def pairs_of(container):
|
|
606
|
+
if isinstance(container, dict):
|
|
607
|
+
return list(container.items())
|
|
608
|
+
return list(container)
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
def read_file(path):
|
|
612
|
+
try:
|
|
613
|
+
with open(path, encoding="utf-8") as f:
|
|
614
|
+
return f.read()
|
|
615
|
+
except FileNotFoundError:
|
|
616
|
+
raise MissingValue('There is no file "%s" (looked in the folder the program runs in).' % path) from None
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
# ---------------------------------------------------------------- rules and tests
|
|
620
|
+
|
|
621
|
+
def never(broken, text, rule=0, value=None):
|
|
622
|
+
"""A Never rule: raise RuleBroken when the forbidden thing has happened."""
|
|
623
|
+
if broken:
|
|
624
|
+
raise RuleBroken("%s (the rule on line %d), but the value is %s." % (text, rule, show(value)))
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def expect_true(ok, text):
|
|
629
|
+
if ok is not True:
|
|
630
|
+
raise ExpectationFailed("%s, but it was not true." % text)
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
_CHECKS = {
|
|
634
|
+
"is": lambda a, b: a == b,
|
|
635
|
+
"is not": lambda a, b: a != b,
|
|
636
|
+
"at least": lambda a, b: a >= b,
|
|
637
|
+
"at most": lambda a, b: a <= b,
|
|
638
|
+
"more than": lambda a, b: a > b,
|
|
639
|
+
"less than": lambda a, b: a < b,
|
|
640
|
+
"nothing": lambda a, b: a is None,
|
|
641
|
+
"not nothing": lambda a, b: a is not None,
|
|
642
|
+
"empty": lambda a, b: len(a) == 0,
|
|
643
|
+
"positive": lambda a, b: a > 0,
|
|
644
|
+
"negative": lambda a, b: a < 0,
|
|
645
|
+
"zero": lambda a, b: a == 0,
|
|
646
|
+
"between": lambda a, b: b[0] <= a <= b[1],
|
|
647
|
+
"in": lambda a, b: a in b,
|
|
648
|
+
"contains": lambda a, b: b in a,
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def expect_value(actual, check, expected, text):
|
|
653
|
+
negate = check.startswith("not ") and check not in _CHECKS
|
|
654
|
+
ok = _CHECKS[check[4:] if negate else check](actual, expected)
|
|
655
|
+
if negate:
|
|
656
|
+
ok = not ok
|
|
657
|
+
if not ok:
|
|
658
|
+
raise ExpectationFailed("%s, but it was %s." % (text, show(actual)))
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
@contextmanager
|
|
662
|
+
def expect_failure(text, message=None):
|
|
663
|
+
try:
|
|
664
|
+
yield
|
|
665
|
+
except ThunderError as e:
|
|
666
|
+
if message is not None and message not in str(e):
|
|
667
|
+
raise ExpectationFailed('%s, but it failed with "%s".' % (text, e)) from None
|
|
668
|
+
return
|
|
669
|
+
except Exception:
|
|
670
|
+
return
|
|
671
|
+
raise ExpectationFailed("%s, but it did not fail." % text)
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
# ---------------------------------------------------------------- errors in Thunder words
|
|
675
|
+
|
|
676
|
+
def explain(error):
|
|
677
|
+
"""The error as a sentence a person can act on."""
|
|
678
|
+
if isinstance(error, ThunderError):
|
|
679
|
+
return str(error)
|
|
680
|
+
if isinstance(error, (ZeroDivisionError, DivisionByZero)):
|
|
681
|
+
return "You divided by zero."
|
|
682
|
+
if isinstance(error, InvalidOperation):
|
|
683
|
+
return "This calculation has no answer (for example, zero divided by zero)."
|
|
684
|
+
if isinstance(error, KeyError):
|
|
685
|
+
return "There is no entry for %s." % show(error.args[0] if error.args else None)
|
|
686
|
+
if isinstance(error, (TypeError, AttributeError)) and "NoneType" in str(error):
|
|
687
|
+
return "A value was nothing where a value was needed."
|
|
688
|
+
if isinstance(error, TypeError):
|
|
689
|
+
return "Values of different kinds were mixed (%s)." % error
|
|
690
|
+
if isinstance(error, RecursionError):
|
|
691
|
+
return "A function called itself too many times."
|
|
692
|
+
if isinstance(error, FileNotFoundError):
|
|
693
|
+
return "There is no file %s." % error.filename
|
|
694
|
+
return "%s: %s" % (type(error).__name__, error)
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
def _code(error):
|
|
698
|
+
if isinstance(error, ThunderError):
|
|
699
|
+
return error.code
|
|
700
|
+
if isinstance(error, (ZeroDivisionError, DivisionByZero)):
|
|
701
|
+
return "TC501"
|
|
702
|
+
if isinstance(error, (TypeError, AttributeError)) and "NoneType" in str(error):
|
|
703
|
+
return "TC502"
|
|
704
|
+
if isinstance(error, KeyError):
|
|
705
|
+
return "TC503"
|
|
706
|
+
if isinstance(error, TypeError):
|
|
707
|
+
return "TC506"
|
|
708
|
+
return "TC508"
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
_MARK = re.compile(r"#\s*thunder:(\d+)\s*$")
|
|
712
|
+
_SOURCE = re.compile(r"^# Generated by the Thunder compiler from (.+)\.$")
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
def _source_of(filename):
|
|
716
|
+
first = linecache.getline(filename, 1).strip()
|
|
717
|
+
m = _SOURCE.match(first)
|
|
718
|
+
return m.group(1) if m else None
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
def thunder_place(tb):
|
|
722
|
+
"""(thunder file, line, from_python): the innermost generated line the error passed through."""
|
|
723
|
+
frames = traceback.extract_tb(tb)
|
|
724
|
+
innermost_generated = None
|
|
725
|
+
for i in range(len(frames) - 1, -1, -1):
|
|
726
|
+
f = frames[i]
|
|
727
|
+
if f.name == "__setattr__":
|
|
728
|
+
continue
|
|
729
|
+
src = _source_of(f.filename)
|
|
730
|
+
if not src:
|
|
731
|
+
continue
|
|
732
|
+
m = _MARK.search(linecache.getline(f.filename, f.lineno).rstrip())
|
|
733
|
+
if m:
|
|
734
|
+
innermost_generated = (src, int(m.group(1)), i)
|
|
735
|
+
break
|
|
736
|
+
if not innermost_generated:
|
|
737
|
+
return None, None, False
|
|
738
|
+
src, line, i = innermost_generated
|
|
739
|
+
outside = frames[i + 1:]
|
|
740
|
+
from_python = any(_source_of(f.filename) is None and not f.filename.endswith("thunder_runtime.py") and f.filename != "<string>" for f in outside)
|
|
741
|
+
return src, line, from_python
|
|
742
|
+
|
|
743
|
+
|
|
744
|
+
def _callers(tb):
|
|
745
|
+
"""The Thunder lines that led to the error, outermost first (where each function was called from)."""
|
|
746
|
+
lines = []
|
|
747
|
+
for f in traceback.extract_tb(tb):
|
|
748
|
+
if f.name in ("__setattr__", "run", "run_tests") or not _source_of(f.filename):
|
|
749
|
+
continue
|
|
750
|
+
m = _MARK.search(linecache.getline(f.filename, f.lineno).rstrip())
|
|
751
|
+
if m:
|
|
752
|
+
lines.append(int(m.group(1)))
|
|
753
|
+
return lines[:-1]
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
def describe_error(error):
|
|
757
|
+
src, line, from_python = thunder_place(error.__traceback__)
|
|
758
|
+
message = explain(error)
|
|
759
|
+
code = _code(error)
|
|
760
|
+
# Any error Thunder has no words for came from Python code reached through "Use" (TC508), even when that
|
|
761
|
+
# code is built into Python and leaves no Python frame of its own (math.sqrt(-1)).
|
|
762
|
+
if (from_python or code == "TC508") and not isinstance(error, ThunderError):
|
|
763
|
+
message = "Python code used by this line failed: " + message
|
|
764
|
+
code = "TC508"
|
|
765
|
+
where = "%s, line %d" % (src, line) if src else "In the program"
|
|
766
|
+
callers = _callers(error.__traceback__)
|
|
767
|
+
if callers and src:
|
|
768
|
+
where += " (reached from line %s)" % ", then line ".join(str(n) for n in reversed(callers))
|
|
769
|
+
return "%s: %s [%s]" % (where, message, code)
|
|
770
|
+
|
|
771
|
+
|
|
772
|
+
def run(main, file=None):
|
|
773
|
+
"""Runs a generated program; an error is reported against the Thunder line, then the program exits with 1."""
|
|
774
|
+
try:
|
|
775
|
+
main()
|
|
776
|
+
except KeyboardInterrupt:
|
|
777
|
+
raise
|
|
778
|
+
except Exception as error: # noqa: BLE001 - every error is reported in Thunder words
|
|
779
|
+
print(describe_error(error), file=sys.stderr)
|
|
780
|
+
sys.exit(1)
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
def run_tests(modules):
|
|
784
|
+
"""Runs every Test block (THUNDER_TESTS in each module). Prints one line per test; exits 1 if any failed."""
|
|
785
|
+
passed = failed = 0
|
|
786
|
+
for module in modules:
|
|
787
|
+
source = getattr(module, "THUNDER_SOURCE", module.__name__)
|
|
788
|
+
for name, test, line in getattr(module, "THUNDER_TESTS", []):
|
|
789
|
+
try:
|
|
790
|
+
test()
|
|
791
|
+
except Exception as error: # noqa: BLE001
|
|
792
|
+
failed += 1
|
|
793
|
+
print("FAIL %s (%s, line %d)" % (name, source, line))
|
|
794
|
+
print(" " + describe_error(error))
|
|
795
|
+
else:
|
|
796
|
+
passed += 1
|
|
797
|
+
print("PASS %s (%s, line %d)" % (name, source, line))
|
|
798
|
+
total = passed + failed
|
|
799
|
+
print("%d test%s: %d passed, %d failed" % (total, "" if total == 1 else "s", passed, failed))
|
|
800
|
+
sys.exit(1 if failed else 0)
|
|
801
|
+
`;
|