| 1 | #!/usr/bin/env python3 |
| 2 | """Independent exact-number oracle. Python stdlib only; never executes Vile. |
| 3 | |
| 4 | Reproduce: python3 /tmp/vile-bignum-oracles/generate.py |
| 5 | JSON contains exact/type/promotion details; TSV is a small V harness surface. |
| 6 | Finite real expectations are IEEE-754 bits, not printer-specific decimal text. |
| 7 | """ |
| 8 | from collections import Counter |
| 9 | from fractions import Fraction as F |
| 10 | from pathlib import Path |
| 11 | import argparse |
| 12 | import hashlib |
| 13 | import json |
| 14 | import math |
| 15 | import random |
| 16 | import struct |
| 17 | |
| 18 | ROOT = Path(__file__).resolve().parent |
| 19 | MIN_I64 = -(1 << 63) |
| 20 | MAX_I64 = (1 << 63) - 1 |
| 21 | SEED = 0x20261115 |
| 22 | RNG = random.Random(SEED) |
| 23 | CASES = [] |
| 24 | SEEN = {} |
| 25 | |
| 26 | |
| 27 | def exact_text(value): |
| 28 | value = F(value) |
| 29 | return str(value.numerator) if value.denominator == 1 else f'{value.numerator}/{value.denominator}' |
| 30 | |
| 31 | |
| 32 | def exact_metadata(value): |
| 33 | value = F(value) |
| 34 | n, d = value.numerator, value.denominator |
| 35 | if d == 1: |
| 36 | kind = 'integer' if MIN_I64 <= n <= MAX_I64 else 'big_integer' |
| 37 | else: |
| 38 | kind = 'rational' if MIN_I64 <= n <= MAX_I64 and d <= MAX_I64 else 'big_rational' |
| 39 | return {'kind': kind, 'exact': True, 'numerator': str(n), 'denominator': str(d), |
| 40 | 'numerator_bits': abs(n).bit_length(), 'denominator_bits': d.bit_length()} |
| 41 | |
| 42 | |
| 43 | def number(value): |
| 44 | return {'mode': 'write', 'write': exact_text(value), **exact_metadata(value)} |
| 45 | |
| 46 | |
| 47 | def boolean(value): |
| 48 | return {'mode': 'write', 'write': '#t' if value else '#f', 'kind': 'boolean', 'value': bool(value)} |
| 49 | |
| 50 | |
| 51 | def sequence(values): |
| 52 | items = [v if isinstance(v, dict) else number(v) for v in values] |
| 53 | return {'mode': 'write', 'write': '(' + ' '.join(v['write'] for v in items) + ')', |
| 54 | 'kind': 'pair' if items else 'nil', 'items': items} |
| 55 | |
| 56 | |
| 57 | def text(value): |
| 58 | return {'mode': 'write', 'write': json.dumps(value, ensure_ascii=False), 'kind': 'string', 'value': value} |
| 59 | |
| 60 | |
| 61 | def float_bits(value): |
| 62 | return struct.unpack('>Q', struct.pack('>d', value))[0] |
| 63 | |
| 64 | |
| 65 | def real(value): |
| 66 | assert math.isfinite(value) |
| 67 | return {'mode': 'f64_bits', 'kind': 'real', 'exact': False, |
| 68 | 'f64_bits': f'{float_bits(value):016x}', 'decimal_roundtrip': repr(value), |
| 69 | 'represented_exact': exact_metadata(F.from_float(value))} |
| 70 | |
| 71 | |
| 72 | def error(reason): |
| 73 | return {'mode': 'error', 'kind': 'error', 'error_class': 'EvalError', 'reason': reason} |
| 74 | |
| 75 | |
| 76 | def add(category, expression, expected, *, inputs=None, detail=None): |
| 77 | assert '\n' not in expression and '\t' not in expression |
| 78 | if expression in SEEN: |
| 79 | assert SEEN[expression]['expected'] == expected, expression |
| 80 | return |
| 81 | case = {'id': f'big-{len(CASES):04d}', 'category': category, |
| 82 | 'expression': expression, 'expected': expected} |
| 83 | if inputs is not None: |
| 84 | case['inputs'] = [exact_metadata(x) for x in inputs] |
| 85 | if detail is not None: |
| 86 | case['detail'] = detail |
| 87 | CASES.append(case) |
| 88 | SEEN[expression] = case |
| 89 | |
| 90 | |
| 91 | def expr(op, values): |
| 92 | return '(' + op + ((' ' + ' '.join(exact_text(v) for v in values)) if values else '') + ')' |
| 93 | |
| 94 | |
| 95 | def trunc(value): |
| 96 | value = F(value) |
| 97 | q = abs(value.numerator) // value.denominator |
| 98 | return -q if value < 0 else q |
| 99 | |
| 100 | |
| 101 | def ties_even(value): |
| 102 | value = F(value) |
| 103 | lower = value.numerator // value.denominator |
| 104 | delta = value - lower |
| 105 | return lower if delta < F(1, 2) or (delta == F(1, 2) and lower % 2 == 0) else lower + 1 |
| 106 | |
| 107 | |
| 108 | def simplest(lo, hi): |
| 109 | """Continued-fraction interval oracle, with exact inclusive endpoints.""" |
| 110 | lo, hi = sorted((F(lo), F(hi))) |
| 111 | if lo == hi: |
| 112 | return lo |
| 113 | if lo <= 0 <= hi: |
| 114 | return F(0) |
| 115 | if hi < 0: |
| 116 | return -simplest(-hi, -lo) |
| 117 | floor = lo.numerator // lo.denominator |
| 118 | if lo == floor: |
| 119 | return F(floor) |
| 120 | if hi >= floor + 1: |
| 121 | return F(floor + 1) |
| 122 | return floor + 1 / simplest(1 / (hi - floor), 1 / (lo - floor)) |
| 123 | |
| 124 | |
| 125 | def radix_integer(value, radix): |
| 126 | assert radix in (2, 8, 10, 16) |
| 127 | sign = '-' if value < 0 else '' |
| 128 | value = abs(value) |
| 129 | if value == 0: |
| 130 | return '0' |
| 131 | digits = [] |
| 132 | while value: |
| 133 | value, remainder = divmod(value, radix) |
| 134 | digits.append('0123456789abcdef'[remainder]) |
| 135 | return sign + ''.join(reversed(digits)) |
| 136 | |
| 137 | |
| 138 | def radix_fraction(value, radix): |
| 139 | value = F(value) |
| 140 | n = radix_integer(value.numerator, radix) |
| 141 | return n if value.denominator == 1 else n + '/' + radix_integer(value.denominator, radix) |
| 142 | |
| 143 | |
| 144 | def fold(op, values): |
| 145 | values = list(map(F, values)) |
| 146 | if op in ('+', '*'): |
| 147 | acc, rest = (F(0) if op == '+' else F(1)), values |
| 148 | elif len(values) == 1: |
| 149 | acc, rest = (F(0) if op == '-' else F(1)), values |
| 150 | else: |
| 151 | acc, rest = values[0], values[1:] |
| 152 | prefixes = [] |
| 153 | for v in rest: |
| 154 | acc = {'+': lambda: acc + v, '-': lambda: acc - v, |
| 155 | '*': lambda: acc * v, '/': lambda: acc / v}[op]() |
| 156 | prefixes.append(exact_metadata(acc)) |
| 157 | return acc, prefixes |
| 158 | |
| 159 | |
| 160 | def arithmetic(): |
| 161 | boundaries = [MIN_I64 - 1, MIN_I64, MIN_I64 + 1, -1, 0, 1, |
| 162 | MAX_I64 - 1, MAX_I64, MAX_I64 + 1, 1 << 64, |
| 163 | -(1 << 127), (1 << 127) - 1, (1 << 128) + 1, |
| 164 | -((1 << 255) + 17), (1 << 521) - 1] |
| 165 | for n in boundaries: |
| 166 | add('literal-promotion', str(n), number(n), inputs=[n]) |
| 167 | add('unary-arithmetic', expr('-', [n]), number(-n), inputs=[n]) |
| 168 | add('unary-arithmetic', expr('abs', [n]), number(abs(n)), inputs=[n]) |
| 169 | add('parity', expr('even?', [n]), boolean(n % 2 == 0), inputs=[n]) |
| 170 | add('parity', expr('odd?', [n]), boolean(n % 2 != 0), inputs=[n]) |
| 171 | rationals = [F(1, 2), F(-1, 3), F(MIN_I64, 3), F(MAX_I64, MAX_I64 - 1), |
| 172 | F(1, 1 << 63), F(-1, 1 << 63), F(1 << 63, MAX_I64), |
| 173 | F((1 << 129) + 7, (1 << 127) + 3), F(-(1 << 260) - 1, (1 << 131) + 9)] |
| 174 | pool = list(map(F, boundaries)) + rationals |
| 175 | pairs = [(F(MAX_I64), F(1)), (F(MIN_I64), F(-1)), (F(1, 1 << 63), F(1, 1 << 63))] |
| 176 | pairs += [(RNG.choice(pool), RNG.choice(pool)) for _ in range(52)] |
| 177 | for a, b in pairs: |
| 178 | for op in ('+', '-', '*', '/'): |
| 179 | if op == '/' and b == 0: |
| 180 | continue |
| 181 | result, prefixes = fold(op, [a, b]) |
| 182 | add('binary-arithmetic', expr(op, [a, b]), number(result), inputs=[a, b], |
| 183 | detail={'prefixes': prefixes}) |
| 184 | for _ in range(30): |
| 185 | bits = RNG.choice([65, 96, 127, 128, 193, 256, 512]) |
| 186 | n = RNG.getrandbits(bits) * RNG.choice([-1, 1]) |
| 187 | d = RNG.getrandbits(bits // 2) + 1 |
| 188 | multiplier = (1 << RNG.choice([63, 64, 129])) + 3 |
| 189 | add('ratio-reduction', f'(/ {n * multiplier} {d * multiplier})', number(F(n, d)), inputs=[n * multiplier, d * multiplier]) |
| 190 | add('ratio-literal-reduction', f'{n * multiplier}/{d * multiplier}', number(F(n, d)), |
| 191 | detail={'unreduced_numerator': str(n * multiplier), 'unreduced_denominator': str(d * multiplier)}) |
| 192 | a, b = F(n, d), F(d, n or 1) |
| 193 | add('ratio-cross-cancel', expr('*', [a, b]), number(a * b), inputs=[a, b]) |
| 194 | for n, d in [(1, 1 << 63), (2, 1 << 63), (MIN_I64, -1), |
| 195 | (MIN_I64, MIN_I64), (MIN_I64, -(1 << 64)), (0, MIN_I64), |
| 196 | (MAX_I64, MIN_I64), (1 << 128, -(1 << 63)), |
| 197 | ((1 << 128) - 2, (1 << 64) - 1)]: |
| 198 | add('denominator-signed64-edge', f'(/ {n} {d})', number(F(n, d)), inputs=[n, d]) |
| 199 | folds = [('+', []), ('*', []), ('+', [MAX_I64, 1, -1]), |
| 200 | ('+', [MIN_I64, -1, 1]), ('-', [0, MIN_I64, 1]), |
| 201 | ('*', [MAX_I64, MAX_I64, 0]), ('*', [MIN_I64, -1, -1]), |
| 202 | ('*', [F(1 << 63), F(1, 2)]), ('+', [MAX_I64, 1, F(-1, 2)]), |
| 203 | ('/', [F(1, 1 << 63), F(1, 1 << 62), F(1, 2)])] |
| 204 | for _ in range(28): |
| 205 | big = F(RNG.getrandbits(RNG.choice([65, 128, 256])) + (1 << 64), RNG.choice([1, 3, (1 << 65) + 1])) |
| 206 | small = RNG.randint(-100, 100) |
| 207 | folds += [('+', [big, big, -big, -big, small]), |
| 208 | ('*', [big, big, F(1, big.numerator), 0]), |
| 209 | ('-', [small, big, -big])] |
| 210 | for op, values in folds: |
| 211 | result, prefixes = fold(op, values) |
| 212 | add('variadic-fold-cancellation', expr(op, values), number(result), inputs=values, |
| 213 | detail={'prefixes': prefixes, 'big_intermediate': any(x['kind'].startswith('big_') for x in prefixes), |
| 214 | 'has_big_operand': any(exact_metadata(v)['kind'].startswith('big_') for v in values), |
| 215 | 'final_demotes': bool(prefixes) and any(x['kind'].startswith('big_') for x in prefixes) and not exact_metadata(result)['kind'].startswith('big_')}) |
| 216 | |
| 217 | |
| 218 | def division_and_integer_families(): |
| 219 | pairs = [(MIN_I64, -1), (MIN_I64, 3), ((1 << 128) + 3, (1 << 64) + 1), |
| 220 | ((1 << 255) - 1, -(1 << 127) + 7), (0, -(1 << 100))] |
| 221 | for _ in range(13): |
| 222 | pairs.append(((RNG.getrandbits(190) + 1) * RNG.choice([-1, 1]), |
| 223 | (RNG.getrandbits(RNG.choice([63, 65, 127])) + 1) * RNG.choice([-1, 1]))) |
| 224 | for a, b in pairs: |
| 225 | qt, qf = trunc(F(a, b)), a // b |
| 226 | rt, rf = a - qt * b, a - qf * b |
| 227 | assert a == qt * b + rt == qf * b + rf |
| 228 | for name, value in [('quotient', qt), ('remainder', rt), ('modulo', rf), |
| 229 | ('floor-quotient', qf), ('floor-remainder', rf), |
| 230 | ('truncate-quotient', qt), ('truncate-remainder', rt)]: |
| 231 | add('integer-division-signs', expr(name, [a, b]), number(value), inputs=[a, b]) |
| 232 | for name, q, r in [('floor/', qf, rf), ('truncate/', qt, rt)]: |
| 233 | add('multiple-division', f'(call-with-values (lambda () {expr(name, [a, b])}) list)', sequence([q, r]), inputs=[a, b]) |
| 234 | rational_pairs = [(F((1 << 100) + 1, 3), F(-5, (1 << 70) + 3)), |
| 235 | (F(-((1 << 127) + 1), (1 << 64) + 1), F(7, 3)), |
| 236 | (F(1, 1 << 1074), F(-3, 1 << 1000))] |
| 237 | for a, b in rational_pairs: |
| 238 | # Vile deliberately retains the existing integer-only operand domain |
| 239 | # for these division families; exact / itself accepts fractions. |
| 240 | for name in ['floor/', 'truncate/']: |
| 241 | add('integer-division-domain', f'(call-with-values (lambda () {expr(name, [a, b])}) list)', |
| 242 | error('division family requires integer operands'), inputs=[a, b]) |
| 243 | groups = [[], [0], [MIN_I64], [MIN_I64, 0], [MIN_I64, MAX_I64], |
| 244 | [1 << 128, 3 * (1 << 64), -(1 << 96)], [0, (1 << 511) + 1, 0]] |
| 245 | groups += [[(RNG.getrandbits(150) + 1) * RNG.choice([-1, 1]) * 6, |
| 246 | (RNG.getrandbits(100) + 1) * 15, 0 if i % 5 == 0 else -21] for i in range(18)] |
| 247 | for values in groups: |
| 248 | for name, value in [('gcd', math.gcd(*values)), ('lcm', math.lcm(*values))]: |
| 249 | add('gcd-lcm', expr(name, values), number(value), inputs=values) |
| 250 | |
| 251 | |
| 252 | def rounding_roots_powers(): |
| 253 | values = [F(MIN_I64) + F(1, 2), F(MAX_I64) + F(1, 2), F(1 << 127) + F(1, 2), |
| 254 | -F(1 << 127) - F(3, 2), F(1, 1 << 63), -F(1, 1 << 1074)] |
| 255 | values += [F(RNG.getrandbits(150) * RNG.choice([-1, 1]), RNG.choice([2, 3, 4, 17, (1 << 64) + 1])) for _ in range(18)] |
| 256 | values += [F(n, 2) for n in [-7, -5, -3, -1, 1, 3, 5, 7]] |
| 257 | for value in values: |
| 258 | for name, result in [('floor', math.floor(value)), ('ceiling', math.ceil(value)), |
| 259 | ('truncate', trunc(value)), ('round', ties_even(value))]: |
| 260 | assert ties_even(value) == round(value) |
| 261 | add('exact-rounding', expr(name, [value]), number(result), inputs=[value]) |
| 262 | roots = [0, 1, 2, (1 << 32) - 1, 1 << 32, (1 << 63) - 1, 1 << 63, |
| 263 | (1 << 127) + 3, (1 << 255) - 19] |
| 264 | for root in roots: |
| 265 | square = root * root |
| 266 | add('perfect-integer-root', f'(sqrt {square})', number(root), inputs=[square]) |
| 267 | add('square', f'(square {root})', number(square), inputs=[root]) |
| 268 | for delta in [-1, 0, 1]: |
| 269 | n = square + delta |
| 270 | if n < 0: |
| 271 | continue |
| 272 | s = math.isqrt(n) |
| 273 | remainder = n - s * s |
| 274 | assert 0 <= remainder < 2 * s + 1 |
| 275 | add('exact-integer-root-remainder', f'(call-with-values (lambda () (exact-integer-sqrt {n})) list)', sequence([s, remainder]), inputs=[n]) |
| 276 | for n, d in [(1 << 70, 3), ((1 << 130) + 7, (1 << 65) + 3), (1, 1 << 537)]: |
| 277 | q = F(n, d) |
| 278 | add('perfect-rational-root', f'(sqrt {exact_text(q * q)})', number(q), inputs=[q * q]) |
| 279 | power_cases = [(0, 0), (0, 5), (-1, 1025), (2, 63), (2, 64), (2, 1024), (2, -1074), |
| 280 | (F(3, 2), 65), (F(-5, 7), -33), (MIN_I64, -1), (MIN_I64, 2), |
| 281 | (1, 1 << 63), (-1, (1 << 63) + 1), (0, 1 << 63), |
| 282 | (-1, -((1 << 63) + 1)), (1, -(1 << 128))] |
| 283 | power_cases += [(F(RNG.choice([-17, -3, 2, 5, 33]), RNG.choice([1, 2, 7])), RNG.choice([-25, -9, 0, 7, 21, 64])) for _ in range(22)] |
| 284 | for base, power in power_cases: |
| 285 | add('exact-integer-power', f'(expt {exact_text(base)} {power})', number(F(base) ** power), inputs=[base, power]) |
| 286 | intervals = [(F(3, 10), F(1, 10)), (F(1 << 100) + F(2, 3), F(1, 100)), |
| 287 | (F(1, 1 << 1074), F(0)), (F(-7, 3), F(1, 10)), (F(1, 7), F(-1, 100))] |
| 288 | intervals += [(F(RNG.randint(-100000, 100000), RNG.randint(1, 1000)), F(1, RNG.randint(2, 2000))) for _ in range(20)] |
| 289 | for value, tolerance in intervals: |
| 290 | result = simplest(value - abs(tolerance), value + abs(tolerance)) |
| 291 | assert value - abs(tolerance) <= result <= value + abs(tolerance) |
| 292 | # Independently verify denominator minimality for manageable cases. |
| 293 | if result.denominator <= 250: |
| 294 | for d in range(1, result.denominator): |
| 295 | assert math.ceil((value - abs(tolerance)) * d) > math.floor((value + abs(tolerance)) * d) |
| 296 | add('exact-rationalize', expr('rationalize', [value, tolerance]), number(result), inputs=[value, tolerance]) |
| 297 | |
| 298 | |
| 299 | def number_io(): |
| 300 | values = [MIN_I64 - 1, MIN_I64, MAX_I64, MAX_I64 + 1, (1 << 127) + 1, |
| 301 | -((1 << 256) - 1), F(1, 1 << 63), F(MIN_I64, (1 << 63) + 1), |
| 302 | F((1 << 190) + 3, (1 << 127) + 1), F(-1, 1 << 1074)] |
| 303 | for value in values: |
| 304 | for radix in (2, 8, 10, 16): |
| 305 | representation = radix_fraction(value, radix) |
| 306 | quoted = json.dumps(representation) |
| 307 | add('radix-format', f'(number->string {exact_text(value)} {radix})', text(representation), inputs=[value], detail={'radix': radix}) |
| 308 | add('radix-parse', f'(string->number {quoted} {radix})', number(value), inputs=[value], detail={'radix': radix}) |
| 309 | add('radix-roundtrip', f'(string->number (number->string {exact_text(value)} {radix}) {radix})', number(value), inputs=[value], detail={'radix': radix}) |
| 310 | for spelling, value in [('#e1e100', F(10) ** 100), ('#e-1.25e80', -F(125, 100) * F(10) ** 80), |
| 311 | ('#e0.000000000000000000000000000001', F(1, 10 ** 30)), |
| 312 | ('#e100000000000000000000000000000/300000000000000000000000000000', F(1, 3)), |
| 313 | ('#e#x10000000000000000', 1 << 64), ('#x#e-10000000000000000', -(1 << 64))]: |
| 314 | add('exact-prefix-decimal', '(string->number ' + json.dumps(spelling) + ')', number(value)) |
| 315 | |
| 316 | |
| 317 | def finite_f64(): |
| 318 | patterns = [0, 1 << 63, 1, (1 << 63) | 1, 2, 3, 0x000fffffffffffff, |
| 319 | 0x0010000000000000, 0x0010000000000001, 0x3fb999999999999a, |
| 320 | 0x3fd5555555555555, 0x3ff0000000000000, 0x3fefffffffffffff, |
| 321 | 0x3ff0000000000001, 0x4330000000000000, 0x4340000000000000, |
| 322 | 0x43e0000000000000, 0xc3e0000000000000, 0x7fefffffffffffff, |
| 323 | 0xffefffffffffffff] |
| 324 | for _ in range(12): |
| 325 | bits = RNG.getrandbits(64) |
| 326 | if bits & 0x7ff0000000000000 != 0x7ff0000000000000: |
| 327 | patterns.append(bits) |
| 328 | for bits in patterns: |
| 329 | value = struct.unpack('>d', struct.pack('>Q', bits))[0] |
| 330 | q = F.from_float(value) |
| 331 | literal = repr(value) |
| 332 | detail = {'input_f64_bits': f'{bits:016x}', 'fraction_from_float': exact_text(q)} |
| 333 | add('finite-f64-to-exact', f'(exact {literal})', number(q), detail=detail) |
| 334 | add('finite-f64-to-exact', f'(inexact->exact {literal})', number(q), detail=detail) |
| 335 | neighbor = math.nextafter(value, math.inf) |
| 336 | if not math.isfinite(neighbor): |
| 337 | neighbor = math.nextafter(value, -math.inf) |
| 338 | epsilon = abs(F.from_float(neighbor) - q) / 4 |
| 339 | low, high = q - epsilon, q + epsilon |
| 340 | source = f'(list (= {exact_text(q)} {literal}) (< {exact_text(low)} {literal}) (> {exact_text(high)} {literal}) (= {exact_text(low)} {literal}) (= {literal} {exact_text(high)}))' |
| 341 | add('finite-f64-exact-comparison', source, sequence(list(map(boolean, [True, True, True, False, False]))), |
| 342 | detail={**detail, 'epsilon': exact_text(epsilon), 'exact_low': exact_text(low), 'exact_high': exact_text(high)}) |
| 343 | if bits != 1 << 63: |
| 344 | # Exact arithmetic has no signed zero; -0.0 -> exact0 -> +0.0. |
| 345 | add('exact-fraction-to-f64', f'(inexact {exact_text(q)})', real(float(q)), inputs=[q], detail=detail) |
| 346 | max_finite = F.from_float(float.fromhex('0x1.fffffffffffffp+1023')) |
| 347 | values = [F(1, 3), F(-1, 10), F(MAX_I64), F(MIN_I64), F((1 << 53) + 1), |
| 348 | F(1, 1 << 1075), F(-1, 1 << 1075), F(3, 1 << 1075), |
| 349 | F(-3, 1 << 1075), F(1, 1 << 1076), F((1 << 100) + 1, (1 << 100) - 1), |
| 350 | max_finite, max_finite + (1 << 969), max_finite + (1 << 970), F(1 << 1024), -F(1 << 1024)] |
| 351 | for value in values: |
| 352 | try: |
| 353 | answer = float(value) |
| 354 | expected = real(answer) if math.isfinite(answer) else error('exact value does not convert to a finite f64') |
| 355 | except OverflowError: |
| 356 | expected = error('exact value does not convert to a finite f64') |
| 357 | for name in ['inexact', 'exact->inexact']: |
| 358 | add('exact-fraction-to-f64-boundaries', expr(name, [value]), expected, inputs=[value]) |
| 359 | |
| 360 | |
| 361 | def domain_errors(): |
| 362 | for spelling in ['+inf.0', '-inf.0', '+nan.0', '-nan.0']: |
| 363 | for name in ['exact', 'inexact->exact']: |
| 364 | add('nonfinite-to-exact-error', f'({name} (string->number {json.dumps(spelling)}))', error('nonfinite input cannot be made exact')) |
| 365 | for expression, reason in [ |
| 366 | ('(/ 1 0)', 'division by zero'), ('(/ 0)', 'division by zero'), |
| 367 | ('(quotient 18446744073709551616 0)', 'division by zero'), |
| 368 | ('(remainder 18446744073709551616 0)', 'division by zero'), |
| 369 | ('(modulo 18446744073709551616 0)', 'division by zero'), |
| 370 | ('(floor-quotient 18446744073709551616 0)', 'division by zero'), |
| 371 | ('(truncate-remainder 18446744073709551616 0)', 'division by zero'), |
| 372 | ('(exact-integer-sqrt -18446744073709551616)', 'negative exact integer root'), |
| 373 | ('(sqrt -18446744073709551616)', 'negative real root now supported as an exact complex'), |
| 374 | ('(expt 0 -18446744073709551616)', 'zero to a negative power'), |
| 375 | ('(* 18446744073709551616 0 #f)', 'late zero does not excuse nonnumeric operand'), |
| 376 | ('(+ 18446744073709551616 -18446744073709551616 #f)', 'cancellation does not excuse nonnumeric operand'), |
| 377 | ('(gcd 18446744073709551616 1/2)', 'GCD requires integers'), |
| 378 | ('(floor-quotient 3/2 1)', 'division family requires integer operands'), |
| 379 | ('(truncate-remainder 1 3/2)', 'division family requires integer operands'), |
| 380 | ('(lcm 0 1/2)', 'zero does not excuse noninteger LCM operand'), |
| 381 | ('(even? 18446744073709551617/2)', 'parity requires integer'), |
| 382 | ]: |
| 383 | if expression == '(sqrt -18446744073709551616)': |
| 384 | imaginary = math.isqrt(1 << 64) |
| 385 | add('negative-big-root', expression, {'mode': 'write', 'write': f'0+{imaginary}i', 'kind': 'exact_complex', 'exact': True}, detail={'rule': 'principal root of -2^64 has imaginary component isqrt(2^64)'}) |
| 386 | else: |
| 387 | add('numeric-domain-error', expression, error(reason)) |
| 388 | |
| 389 | |
| 390 | def main(output): |
| 391 | output.mkdir(parents=True, exist_ok=True) |
| 392 | arithmetic() |
| 393 | division_and_integer_families() |
| 394 | rounding_roots_powers() |
| 395 | number_io() |
| 396 | finite_f64() |
| 397 | domain_errors() |
| 398 | payload = {'schema': 1, 'seed': SEED, 'oracle': 'Python stdlib int, fractions.Fraction, math.isqrt/gcd/lcm, Fraction.from_float', |
| 399 | 'canonical_tags': {'integer': 'signed64 integer', 'big_integer': 'integer outside signed64', |
| 400 | 'rational': 'reduced noninteger, signed64 numerator and positive denominator <=2^63-1', |
| 401 | 'big_rational': 'other reduced exact noninteger', |
| 402 | 'exact_complex': 'nonzero imaginary, exact rational components (negative-root extension case)'}, |
| 403 | 'tsv_columns': ['id', 'category', 'expression', 'expectation_mode', 'expected_write', 'expected_kind', 'expected_f64_bits'], |
| 404 | 'counts': {'total': len(CASES), 'by_category': dict(sorted(Counter(c['category'] for c in CASES).items())), |
| 405 | 'by_expected_kind': dict(sorted(Counter(c['expected']['kind'] for c in CASES).items()))}, |
| 406 | 'cases': CASES} |
| 407 | json_path = output / 'bignum_cases.json' |
| 408 | json_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + '\n') |
| 409 | rows = ['# ' + '\t'.join(payload['tsv_columns'])] |
| 410 | for case in CASES: |
| 411 | expected = case['expected'] |
| 412 | rows.append('\t'.join([case['id'], case['category'], case['expression'], expected['mode'], |
| 413 | expected.get('write', ''), expected['kind'], expected.get('f64_bits', '')])) |
| 414 | tsv_path = output / 'bignum_cases.tsv' |
| 415 | tsv_path.write_text('\n'.join(rows) + '\n') |
| 416 | manifest = {'generator_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), |
| 417 | 'seed': SEED, 'counts': payload['counts'], |
| 418 | 'files': {path.name: {'sha256': hashlib.sha256(path.read_bytes()).hexdigest(), 'bytes': path.stat().st_size} |
| 419 | for path in [json_path, tsv_path]}} |
| 420 | (output / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n') |
| 421 | print(json.dumps(manifest, indent=2)) |
| 422 | |
| 423 | |
| 424 | if __name__ == '__main__': |
| 425 | parser = argparse.ArgumentParser(description=__doc__) |
| 426 | parser.add_argument('--output', type=Path, default=ROOT) |
| 427 | main(parser.parse_args().output) |
| 428 | |