# SPDX-License-Identifier: GPL-3.0-or-later """Qualify bounded fixed-decimal output using exact BASIC-float test vectors.""" import argparse from fractions import Fraction import os from pathlib import Path import shutil import subprocess import tempfile def floor_code(value): """Positive BASIC encoding at or immediately below a positive rational.""" exponent = value.numerator.bit_length() - value.denominator.bit_length() if Fraction(2) ** exponent > value: exponent -= 1 significand = int(value * Fraction(2) ** (31 - exponent)) return ((exponent + 129) << 31) + significand - (1 << 31) def write_vectors(path): # Changing this positive encoding by one steps one representable value, # including across a power of two. Exercise both signs of each input. cases = set() for places in range(4): scale = 10 ** places centers = [Fraction(n, 2 * scale) for n in (1, 3, 19, 20 * scale - 1, 131072 * scale - 1)] centers.extend([Fraction(1, 2 ** (places + 1)), Fraction(65536)]) codes = {0, 1 << 31, (256 << 31) - 1} for center in centers: code = floor_code(center) codes.update((code - 1, code, code + 1)) for code in codes: for negative in (False, True): cases.add((code, negative, places)) cases.update([(floor_code(Fraction(1)), False, 4), (0, False, 255)]) rows = [] for code, negative, places in sorted(cases): exp, fraction = divmod(code, 1 << 31) magnitude = Fraction((1 << 31) + fraction) * Fraction(2) ** (exp - 160) if exp else Fraction(0) packed = bytes([exp]) + (fraction | (int(negative) << 31)).to_bytes(4, 'big') expected = 'NULL' if magnitude < 65536 and places <= 3: scale = 10 ** places rounded = int(magnitude * scale + Fraction(1, 2)) whole, tail = divmod(rounded, scale) sign = '-' if rounded and negative else '' decimal = f'.{tail:0{places}d}' if places else '' expected = f'"{sign}{whole}{decimal}"' octets = ', '.join(f'0x{b:02x}' for b in packed) rows.append(f' {{ {{ {octets} }}, {places}, {expected} }},') path.write_text('\n'.join(rows) + '\n') return len(rows) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('runtime', type=Path) parser.add_argument('core', type=Path) parser.add_argument('roms', type=Path) parser.add_argument('--capture', type=Path, help="save the optimized 6809 guest display as a PNG") args = parser.parse_args() runtime, core, roms = (p.resolve(strict=True) for p in (args.runtime, args.core, args.roms)) fixture = Path(__file__).resolve().parent root = fixture.parents[2] env = dict(os.environ, VCC_CMOC_COMPAT="1", PATH=str(runtime / "bin") + os.pathsep + os.environ["PATH"]) with tempfile.TemporaryDirectory(prefix="vcc-descent-") as temp: work = Path(temp) def run(*cmd): subprocess.run(cmd, cwd=work, env=env, check=True) print(f'{write_vectors(work / "vectors.inc")} exact rational vectors', flush=True) shutil.copyfile(fixture / 'qualification.c', work / 'qualification.c') run('xcrun', 'clang++', '-std=c++17', '-O2', '-mmacosx-version-min=14.0', '-I', root / 'src', fixture / 'run.cpp', core, '-o', 'run') cmoc = runtime / 'bin/cmoc' descent = root / 'examples/cmoc/manual/descent.c' # These are the two edits readers can try in the chapter. source = descent.read_text() (work / 'level.c').write_text(source.replace('report(105.50f,', 'report(101.75f,')) (work / 'short.c').write_text(source.replace('char field[12]', 'char field[5]')) for opt in ('-O0', '-O2'): build = [cmoc, '--coco', '--org=2800', '-Werror', opt] run(*build, '-o', 'QUAL.BIN', 'qualification.c', '-lvcccompat') if opt == '-O0': # Production archive objects always use -O2. Also build the # formatter itself without optimization to catch compiler issues. run(*build, '-c', '-o', 'fixed-plain.o', root / 'sdk/cmoc/compat/fixed.c') run(*build, '-o', 'PLAIN.BIN', 'qualification.c', 'fixed-plain.o') run(*build, '--intermediate', '-o', 'DESCENT.BIN', descent, '-lvcccompat') for name in ('level', 'short'): run(*build, '-o', name.upper() + '.BIN', name + '.c', '-lvcccompat') shutil.copyfile(root / 'docs/manuals/software-storage-and-peripherals/media/BLANK.DSK', work / 'VOL.DSK') run(runtime / 'bin/writecocofile', 'VOL.DSK', 'DESCENT.BIN') print(f'{opt}: DESCENT.BIN {(work / "DESCENT.BIN").stat().st_size} bytes', flush=True) for line in (work / 'DESCENT.map').read_text().splitlines(): if line.startswith('Section: ') and '(fixed.o)' in line: print(line, flush=True) capture = args.capture and opt == '-O2' run('./run', roms, opt, *(['capture'] if capture else [])) if capture: run('sips', '-s', 'format', 'png', 'descent.ppm', '--out', args.capture.resolve()) # Linking vcccompat for an integer-only report must not charge this object. (work / 'integer.c').write_text('#include \nint main(void) {\n' ' char out[4]; return snprintf(out, sizeof(out), "%d", 12);\n}\n') run(cmoc, '--coco', '-O2', '--intermediate', '-Werror', '-o', 'INTEGER.BIN', 'integer.c', '-lvcccompat') if '(fixed.o)' in (work / 'INTEGER.map').read_text(): raise AssertionError('Integer-only report linked the floating-point formatter') if __name__ == '__main__': main()