#!/usr/bin/env python3 """Independent exact-number oracle. Python stdlib only; never executes Vile. Reproduce: python3 /tmp/vile-bignum-oracles/generate.py JSON contains exact/type/promotion details; TSV is a small V harness surface. Finite real expectations are IEEE-754 bits, not printer-specific decimal text. """ from collections import Counter from fractions import Fraction as F from pathlib import Path import argparse import hashlib import json import math import random import struct ROOT = Path(__file__).resolve().parent MIN_I64 = -(1 << 63) MAX_I64 = (1 << 63) - 1 SEED = 0x20261115 RNG = random.Random(SEED) CASES = [] SEEN = {} def exact_text(value): value = F(value) return str(value.numerator) if value.denominator == 1 else f'{value.numerator}/{value.denominator}' def exact_metadata(value): value = F(value) n, d = value.numerator, value.denominator if d == 1: kind = 'integer' if MIN_I64 <= n <= MAX_I64 else 'big_integer' else: kind = 'rational' if MIN_I64 <= n <= MAX_I64 and d <= MAX_I64 else 'big_rational' return {'kind': kind, 'exact': True, 'numerator': str(n), 'denominator': str(d), 'numerator_bits': abs(n).bit_length(), 'denominator_bits': d.bit_length()} def number(value): return {'mode': 'write', 'write': exact_text(value), **exact_metadata(value)} def boolean(value): return {'mode': 'write', 'write': '#t' if value else '#f', 'kind': 'boolean', 'value': bool(value)} def sequence(values): items = [v if isinstance(v, dict) else number(v) for v in values] return {'mode': 'write', 'write': '(' + ' '.join(v['write'] for v in items) + ')', 'kind': 'pair' if items else 'nil', 'items': items} def text(value): return {'mode': 'write', 'write': json.dumps(value, ensure_ascii=False), 'kind': 'string', 'value': value} def float_bits(value): return struct.unpack('>Q', struct.pack('>d', value))[0] def real(value): assert math.isfinite(value) return {'mode': 'f64_bits', 'kind': 'real', 'exact': False, 'f64_bits': f'{float_bits(value):016x}', 'decimal_roundtrip': repr(value), 'represented_exact': exact_metadata(F.from_float(value))} def error(reason): return {'mode': 'error', 'kind': 'error', 'error_class': 'EvalError', 'reason': reason} def add(category, expression, expected, *, inputs=None, detail=None): assert '\n' not in expression and '\t' not in expression if expression in SEEN: assert SEEN[expression]['expected'] == expected, expression return case = {'id': f'big-{len(CASES):04d}', 'category': category, 'expression': expression, 'expected': expected} if inputs is not None: case['inputs'] = [exact_metadata(x) for x in inputs] if detail is not None: case['detail'] = detail CASES.append(case) SEEN[expression] = case def expr(op, values): return '(' + op + ((' ' + ' '.join(exact_text(v) for v in values)) if values else '') + ')' def trunc(value): value = F(value) q = abs(value.numerator) // value.denominator return -q if value < 0 else q def ties_even(value): value = F(value) lower = value.numerator // value.denominator delta = value - lower return lower if delta < F(1, 2) or (delta == F(1, 2) and lower % 2 == 0) else lower + 1 def simplest(lo, hi): """Continued-fraction interval oracle, with exact inclusive endpoints.""" lo, hi = sorted((F(lo), F(hi))) if lo == hi: return lo if lo <= 0 <= hi: return F(0) if hi < 0: return -simplest(-hi, -lo) floor = lo.numerator // lo.denominator if lo == floor: return F(floor) if hi >= floor + 1: return F(floor + 1) return floor + 1 / simplest(1 / (hi - floor), 1 / (lo - floor)) def radix_integer(value, radix): assert radix in (2, 8, 10, 16) sign = '-' if value < 0 else '' value = abs(value) if value == 0: return '0' digits = [] while value: value, remainder = divmod(value, radix) digits.append('0123456789abcdef'[remainder]) return sign + ''.join(reversed(digits)) def radix_fraction(value, radix): value = F(value) n = radix_integer(value.numerator, radix) return n if value.denominator == 1 else n + '/' + radix_integer(value.denominator, radix) def fold(op, values): values = list(map(F, values)) if op in ('+', '*'): acc, rest = (F(0) if op == '+' else F(1)), values elif len(values) == 1: acc, rest = (F(0) if op == '-' else F(1)), values else: acc, rest = values[0], values[1:] prefixes = [] for v in rest: acc = {'+': lambda: acc + v, '-': lambda: acc - v, '*': lambda: acc * v, '/': lambda: acc / v}[op]() prefixes.append(exact_metadata(acc)) return acc, prefixes def arithmetic(): boundaries = [MIN_I64 - 1, MIN_I64, MIN_I64 + 1, -1, 0, 1, MAX_I64 - 1, MAX_I64, MAX_I64 + 1, 1 << 64, -(1 << 127), (1 << 127) - 1, (1 << 128) + 1, -((1 << 255) + 17), (1 << 521) - 1] for n in boundaries: add('literal-promotion', str(n), number(n), inputs=[n]) add('unary-arithmetic', expr('-', [n]), number(-n), inputs=[n]) add('unary-arithmetic', expr('abs', [n]), number(abs(n)), inputs=[n]) add('parity', expr('even?', [n]), boolean(n % 2 == 0), inputs=[n]) add('parity', expr('odd?', [n]), boolean(n % 2 != 0), inputs=[n]) rationals = [F(1, 2), F(-1, 3), F(MIN_I64, 3), F(MAX_I64, MAX_I64 - 1), F(1, 1 << 63), F(-1, 1 << 63), F(1 << 63, MAX_I64), F((1 << 129) + 7, (1 << 127) + 3), F(-(1 << 260) - 1, (1 << 131) + 9)] pool = list(map(F, boundaries)) + rationals pairs = [(F(MAX_I64), F(1)), (F(MIN_I64), F(-1)), (F(1, 1 << 63), F(1, 1 << 63))] pairs += [(RNG.choice(pool), RNG.choice(pool)) for _ in range(52)] for a, b in pairs: for op in ('+', '-', '*', '/'): if op == '/' and b == 0: continue result, prefixes = fold(op, [a, b]) add('binary-arithmetic', expr(op, [a, b]), number(result), inputs=[a, b], detail={'prefixes': prefixes}) for _ in range(30): bits = RNG.choice([65, 96, 127, 128, 193, 256, 512]) n = RNG.getrandbits(bits) * RNG.choice([-1, 1]) d = RNG.getrandbits(bits // 2) + 1 multiplier = (1 << RNG.choice([63, 64, 129])) + 3 add('ratio-reduction', f'(/ {n * multiplier} {d * multiplier})', number(F(n, d)), inputs=[n * multiplier, d * multiplier]) add('ratio-literal-reduction', f'{n * multiplier}/{d * multiplier}', number(F(n, d)), detail={'unreduced_numerator': str(n * multiplier), 'unreduced_denominator': str(d * multiplier)}) a, b = F(n, d), F(d, n or 1) add('ratio-cross-cancel', expr('*', [a, b]), number(a * b), inputs=[a, b]) for n, d in [(1, 1 << 63), (2, 1 << 63), (MIN_I64, -1), (MIN_I64, MIN_I64), (MIN_I64, -(1 << 64)), (0, MIN_I64), (MAX_I64, MIN_I64), (1 << 128, -(1 << 63)), ((1 << 128) - 2, (1 << 64) - 1)]: add('denominator-signed64-edge', f'(/ {n} {d})', number(F(n, d)), inputs=[n, d]) folds = [('+', []), ('*', []), ('+', [MAX_I64, 1, -1]), ('+', [MIN_I64, -1, 1]), ('-', [0, MIN_I64, 1]), ('*', [MAX_I64, MAX_I64, 0]), ('*', [MIN_I64, -1, -1]), ('*', [F(1 << 63), F(1, 2)]), ('+', [MAX_I64, 1, F(-1, 2)]), ('/', [F(1, 1 << 63), F(1, 1 << 62), F(1, 2)])] for _ in range(28): big = F(RNG.getrandbits(RNG.choice([65, 128, 256])) + (1 << 64), RNG.choice([1, 3, (1 << 65) + 1])) small = RNG.randint(-100, 100) folds += [('+', [big, big, -big, -big, small]), ('*', [big, big, F(1, big.numerator), 0]), ('-', [small, big, -big])] for op, values in folds: result, prefixes = fold(op, values) add('variadic-fold-cancellation', expr(op, values), number(result), inputs=values, detail={'prefixes': prefixes, 'big_intermediate': any(x['kind'].startswith('big_') for x in prefixes), 'has_big_operand': any(exact_metadata(v)['kind'].startswith('big_') for v in values), 'final_demotes': bool(prefixes) and any(x['kind'].startswith('big_') for x in prefixes) and not exact_metadata(result)['kind'].startswith('big_')}) def division_and_integer_families(): pairs = [(MIN_I64, -1), (MIN_I64, 3), ((1 << 128) + 3, (1 << 64) + 1), ((1 << 255) - 1, -(1 << 127) + 7), (0, -(1 << 100))] for _ in range(13): pairs.append(((RNG.getrandbits(190) + 1) * RNG.choice([-1, 1]), (RNG.getrandbits(RNG.choice([63, 65, 127])) + 1) * RNG.choice([-1, 1]))) for a, b in pairs: qt, qf = trunc(F(a, b)), a // b rt, rf = a - qt * b, a - qf * b assert a == qt * b + rt == qf * b + rf for name, value in [('quotient', qt), ('remainder', rt), ('modulo', rf), ('floor-quotient', qf), ('floor-remainder', rf), ('truncate-quotient', qt), ('truncate-remainder', rt)]: add('integer-division-signs', expr(name, [a, b]), number(value), inputs=[a, b]) for name, q, r in [('floor/', qf, rf), ('truncate/', qt, rt)]: add('multiple-division', f'(call-with-values (lambda () {expr(name, [a, b])}) list)', sequence([q, r]), inputs=[a, b]) rational_pairs = [(F((1 << 100) + 1, 3), F(-5, (1 << 70) + 3)), (F(-((1 << 127) + 1), (1 << 64) + 1), F(7, 3)), (F(1, 1 << 1074), F(-3, 1 << 1000))] for a, b in rational_pairs: # Vile deliberately retains the existing integer-only operand domain # for these division families; exact / itself accepts fractions. for name in ['floor/', 'truncate/']: add('integer-division-domain', f'(call-with-values (lambda () {expr(name, [a, b])}) list)', error('division family requires integer operands'), inputs=[a, b]) groups = [[], [0], [MIN_I64], [MIN_I64, 0], [MIN_I64, MAX_I64], [1 << 128, 3 * (1 << 64), -(1 << 96)], [0, (1 << 511) + 1, 0]] groups += [[(RNG.getrandbits(150) + 1) * RNG.choice([-1, 1]) * 6, (RNG.getrandbits(100) + 1) * 15, 0 if i % 5 == 0 else -21] for i in range(18)] for values in groups: for name, value in [('gcd', math.gcd(*values)), ('lcm', math.lcm(*values))]: add('gcd-lcm', expr(name, values), number(value), inputs=values) def rounding_roots_powers(): values = [F(MIN_I64) + F(1, 2), F(MAX_I64) + F(1, 2), F(1 << 127) + F(1, 2), -F(1 << 127) - F(3, 2), F(1, 1 << 63), -F(1, 1 << 1074)] values += [F(RNG.getrandbits(150) * RNG.choice([-1, 1]), RNG.choice([2, 3, 4, 17, (1 << 64) + 1])) for _ in range(18)] values += [F(n, 2) for n in [-7, -5, -3, -1, 1, 3, 5, 7]] for value in values: for name, result in [('floor', math.floor(value)), ('ceiling', math.ceil(value)), ('truncate', trunc(value)), ('round', ties_even(value))]: assert ties_even(value) == round(value) add('exact-rounding', expr(name, [value]), number(result), inputs=[value]) roots = [0, 1, 2, (1 << 32) - 1, 1 << 32, (1 << 63) - 1, 1 << 63, (1 << 127) + 3, (1 << 255) - 19] for root in roots: square = root * root add('perfect-integer-root', f'(sqrt {square})', number(root), inputs=[square]) add('square', f'(square {root})', number(square), inputs=[root]) for delta in [-1, 0, 1]: n = square + delta if n < 0: continue s = math.isqrt(n) remainder = n - s * s assert 0 <= remainder < 2 * s + 1 add('exact-integer-root-remainder', f'(call-with-values (lambda () (exact-integer-sqrt {n})) list)', sequence([s, remainder]), inputs=[n]) for n, d in [(1 << 70, 3), ((1 << 130) + 7, (1 << 65) + 3), (1, 1 << 537)]: q = F(n, d) add('perfect-rational-root', f'(sqrt {exact_text(q * q)})', number(q), inputs=[q * q]) power_cases = [(0, 0), (0, 5), (-1, 1025), (2, 63), (2, 64), (2, 1024), (2, -1074), (F(3, 2), 65), (F(-5, 7), -33), (MIN_I64, -1), (MIN_I64, 2), (1, 1 << 63), (-1, (1 << 63) + 1), (0, 1 << 63), (-1, -((1 << 63) + 1)), (1, -(1 << 128))] 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)] for base, power in power_cases: add('exact-integer-power', f'(expt {exact_text(base)} {power})', number(F(base) ** power), inputs=[base, power]) intervals = [(F(3, 10), F(1, 10)), (F(1 << 100) + F(2, 3), F(1, 100)), (F(1, 1 << 1074), F(0)), (F(-7, 3), F(1, 10)), (F(1, 7), F(-1, 100))] intervals += [(F(RNG.randint(-100000, 100000), RNG.randint(1, 1000)), F(1, RNG.randint(2, 2000))) for _ in range(20)] for value, tolerance in intervals: result = simplest(value - abs(tolerance), value + abs(tolerance)) assert value - abs(tolerance) <= result <= value + abs(tolerance) # Independently verify denominator minimality for manageable cases. if result.denominator <= 250: for d in range(1, result.denominator): assert math.ceil((value - abs(tolerance)) * d) > math.floor((value + abs(tolerance)) * d) add('exact-rationalize', expr('rationalize', [value, tolerance]), number(result), inputs=[value, tolerance]) def number_io(): values = [MIN_I64 - 1, MIN_I64, MAX_I64, MAX_I64 + 1, (1 << 127) + 1, -((1 << 256) - 1), F(1, 1 << 63), F(MIN_I64, (1 << 63) + 1), F((1 << 190) + 3, (1 << 127) + 1), F(-1, 1 << 1074)] for value in values: for radix in (2, 8, 10, 16): representation = radix_fraction(value, radix) quoted = json.dumps(representation) add('radix-format', f'(number->string {exact_text(value)} {radix})', text(representation), inputs=[value], detail={'radix': radix}) add('radix-parse', f'(string->number {quoted} {radix})', number(value), inputs=[value], detail={'radix': radix}) add('radix-roundtrip', f'(string->number (number->string {exact_text(value)} {radix}) {radix})', number(value), inputs=[value], detail={'radix': radix}) for spelling, value in [('#e1e100', F(10) ** 100), ('#e-1.25e80', -F(125, 100) * F(10) ** 80), ('#e0.000000000000000000000000000001', F(1, 10 ** 30)), ('#e100000000000000000000000000000/300000000000000000000000000000', F(1, 3)), ('#e#x10000000000000000', 1 << 64), ('#x#e-10000000000000000', -(1 << 64))]: add('exact-prefix-decimal', '(string->number ' + json.dumps(spelling) + ')', number(value)) def finite_f64(): patterns = [0, 1 << 63, 1, (1 << 63) | 1, 2, 3, 0x000fffffffffffff, 0x0010000000000000, 0x0010000000000001, 0x3fb999999999999a, 0x3fd5555555555555, 0x3ff0000000000000, 0x3fefffffffffffff, 0x3ff0000000000001, 0x4330000000000000, 0x4340000000000000, 0x43e0000000000000, 0xc3e0000000000000, 0x7fefffffffffffff, 0xffefffffffffffff] for _ in range(12): bits = RNG.getrandbits(64) if bits & 0x7ff0000000000000 != 0x7ff0000000000000: patterns.append(bits) for bits in patterns: value = struct.unpack('>d', struct.pack('>Q', bits))[0] q = F.from_float(value) literal = repr(value) detail = {'input_f64_bits': f'{bits:016x}', 'fraction_from_float': exact_text(q)} add('finite-f64-to-exact', f'(exact {literal})', number(q), detail=detail) add('finite-f64-to-exact', f'(inexact->exact {literal})', number(q), detail=detail) neighbor = math.nextafter(value, math.inf) if not math.isfinite(neighbor): neighbor = math.nextafter(value, -math.inf) epsilon = abs(F.from_float(neighbor) - q) / 4 low, high = q - epsilon, q + epsilon source = f'(list (= {exact_text(q)} {literal}) (< {exact_text(low)} {literal}) (> {exact_text(high)} {literal}) (= {exact_text(low)} {literal}) (= {literal} {exact_text(high)}))' add('finite-f64-exact-comparison', source, sequence(list(map(boolean, [True, True, True, False, False]))), detail={**detail, 'epsilon': exact_text(epsilon), 'exact_low': exact_text(low), 'exact_high': exact_text(high)}) if bits != 1 << 63: # Exact arithmetic has no signed zero; -0.0 -> exact0 -> +0.0. add('exact-fraction-to-f64', f'(inexact {exact_text(q)})', real(float(q)), inputs=[q], detail=detail) max_finite = F.from_float(float.fromhex('0x1.fffffffffffffp+1023')) values = [F(1, 3), F(-1, 10), F(MAX_I64), F(MIN_I64), F((1 << 53) + 1), F(1, 1 << 1075), F(-1, 1 << 1075), F(3, 1 << 1075), F(-3, 1 << 1075), F(1, 1 << 1076), F((1 << 100) + 1, (1 << 100) - 1), max_finite, max_finite + (1 << 969), max_finite + (1 << 970), F(1 << 1024), -F(1 << 1024)] for value in values: try: answer = float(value) expected = real(answer) if math.isfinite(answer) else error('exact value does not convert to a finite f64') except OverflowError: expected = error('exact value does not convert to a finite f64') for name in ['inexact', 'exact->inexact']: add('exact-fraction-to-f64-boundaries', expr(name, [value]), expected, inputs=[value]) def domain_errors(): for spelling in ['+inf.0', '-inf.0', '+nan.0', '-nan.0']: for name in ['exact', 'inexact->exact']: add('nonfinite-to-exact-error', f'({name} (string->number {json.dumps(spelling)}))', error('nonfinite input cannot be made exact')) for expression, reason in [ ('(/ 1 0)', 'division by zero'), ('(/ 0)', 'division by zero'), ('(quotient 18446744073709551616 0)', 'division by zero'), ('(remainder 18446744073709551616 0)', 'division by zero'), ('(modulo 18446744073709551616 0)', 'division by zero'), ('(floor-quotient 18446744073709551616 0)', 'division by zero'), ('(truncate-remainder 18446744073709551616 0)', 'division by zero'), ('(exact-integer-sqrt -18446744073709551616)', 'negative exact integer root'), ('(sqrt -18446744073709551616)', 'negative real root now supported as an exact complex'), ('(expt 0 -18446744073709551616)', 'zero to a negative power'), ('(* 18446744073709551616 0 #f)', 'late zero does not excuse nonnumeric operand'), ('(+ 18446744073709551616 -18446744073709551616 #f)', 'cancellation does not excuse nonnumeric operand'), ('(gcd 18446744073709551616 1/2)', 'GCD requires integers'), ('(floor-quotient 3/2 1)', 'division family requires integer operands'), ('(truncate-remainder 1 3/2)', 'division family requires integer operands'), ('(lcm 0 1/2)', 'zero does not excuse noninteger LCM operand'), ('(even? 18446744073709551617/2)', 'parity requires integer'), ]: if expression == '(sqrt -18446744073709551616)': imaginary = math.isqrt(1 << 64) 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)'}) else: add('numeric-domain-error', expression, error(reason)) def main(output): output.mkdir(parents=True, exist_ok=True) arithmetic() division_and_integer_families() rounding_roots_powers() number_io() finite_f64() domain_errors() payload = {'schema': 1, 'seed': SEED, 'oracle': 'Python stdlib int, fractions.Fraction, math.isqrt/gcd/lcm, Fraction.from_float', 'canonical_tags': {'integer': 'signed64 integer', 'big_integer': 'integer outside signed64', 'rational': 'reduced noninteger, signed64 numerator and positive denominator <=2^63-1', 'big_rational': 'other reduced exact noninteger', 'exact_complex': 'nonzero imaginary, exact rational components (negative-root extension case)'}, 'tsv_columns': ['id', 'category', 'expression', 'expectation_mode', 'expected_write', 'expected_kind', 'expected_f64_bits'], 'counts': {'total': len(CASES), 'by_category': dict(sorted(Counter(c['category'] for c in CASES).items())), 'by_expected_kind': dict(sorted(Counter(c['expected']['kind'] for c in CASES).items()))}, 'cases': CASES} json_path = output / 'bignum_cases.json' json_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + '\n') rows = ['# ' + '\t'.join(payload['tsv_columns'])] for case in CASES: expected = case['expected'] rows.append('\t'.join([case['id'], case['category'], case['expression'], expected['mode'], expected.get('write', ''), expected['kind'], expected.get('f64_bits', '')])) tsv_path = output / 'bignum_cases.tsv' tsv_path.write_text('\n'.join(rows) + '\n') manifest = {'generator_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), 'seed': SEED, 'counts': payload['counts'], 'files': {path.name: {'sha256': hashlib.sha256(path.read_bytes()).hexdigest(), 'bytes': path.stat().st_size} for path in [json_path, tsv_path]}} (output / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n') print(json.dumps(manifest, indent=2)) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--output', type=Path, default=ROOT) main(parser.parse_args().output)