#!/usr/bin/env python3
import argparse


MASK64 = (1 << 64) - 1
MASK32 = (1 << 32) - 1
SIGNATURE_SEED = 0x16600132
GROUP_SIGNATURE_SEED = 0xF84D0000
ITERATIONS = 256
CHECKPOINT_INTERVAL = 8
SUITE_ID = 328
SEEDS = (
    0x1660F84D1B2C3D4E,
    0xC16684D05EED1234,
    0x5EEDF84D89ABCDEF,
)
EDGES = (
    0x0000000000000000,
    0x8000000000000000,
    0x0000000000000001,
    0x800FFFFFFFFFFFFF,
    0x0010000000000000,
    0x368FFFFFFFFFFFFF,
    0x3690000000000000,
    0x3690000000000001,
    0x36A0000000000000,
    0x36A7FFFFFFFFFFFF,
    0x36A8000000000000,
    0x36A8000000000001,
    0x380FFFFFC0000000,
    0x380FFFFFE0000000,
    0x3810000000000000,
    0x3FF0000010000000,
    0x3FF0000010000001,
    0x3FF0000030000000,
    0xBFF0000010000000,
    0x47EFFFFFE0000000,
    0x47EFFFFFEFFFFFFF,
    0x47EFFFFFFFF00000,
    0x47EFFFFFFFF00001,
    0x7FEFFFFFFFFFFFFF,
    0xFFEFFFFFFFFFFFFF,
    0x7FF0000000000000,
    0xFFF0000000000000,
    0x7FF0000000000001,
    0x7FF8000000000000,
    0x7FF8123456789ABC,
    0xFFF923456789ABCD,
    0xC1DFFFFFFFC00000,
)


def xorshift64(state):
    state ^= state << 13 & MASK64
    state ^= state >> 7
    state ^= state << 17 & MASK64
    return state & MASK64


def input_bits(seed_index, seed):
    state = seed
    for iteration in range(ITERATIONS):
        state = xorshift64(state)
        bits = state
        if iteration % 8 == 0:
            bits = EDGES[(iteration // 8 + seed_index) % len(EDGES)]
        yield iteration, bits


def narrow_bits(bits):
    sign = (bits >> 32) & 0x80000000
    exponent = (bits >> 52) & 0x7FF
    fraction = bits & ((1 << 52) - 1)

    if exponent == 0x7FF:
        if fraction == 0:
            return sign | 0x7F800000
        payload = fraction >> 29
        return sign | 0x7F800000 | payload | 0x00400000

    if exponent > 1150:
        return sign | 0x7F800000

    if exponent >= 897:
        destination_exponent = exponent - 896
        destination_fraction = fraction >> 29
        discarded = fraction & ((1 << 29) - 1)
        halfway = 1 << 28
        if (discarded > halfway or
                (discarded == halfway and destination_fraction & 1)):
            destination_fraction += 1
            if destination_fraction == 1 << 23:
                destination_fraction = 0
                destination_exponent += 1
        return (sign | destination_exponent << 23 |
                destination_fraction) & MASK32

    if exponent < 873:
        return sign

    significand = (1 << 52) | fraction
    shift = 926 - exponent
    destination = significand >> shift
    discarded = significand & ((1 << shift) - 1)
    halfway = 1 << (shift - 1)
    if discarded > halfway or (discarded == halfway and destination & 1):
        destination += 1
    return (sign | destination) & MASK32


def signature_step(signature, case_id, value):
    case_id &= 0xFFFF
    tag = case_id << 16 | case_id
    rotated = (signature << 5 | signature >> 27) & MASK32
    return (rotated ^ value ^ tag) & MASK32


def checkpoint_groups():
    groups = []
    for seed_index, seed in enumerate(SEEDS):
        signature = GROUP_SIGNATURE_SEED ^ ((seed_index + 1) << 8)
        checkpoints = []
        for iteration, bits in input_bits(seed_index, seed):
            signature = signature_step(
                signature, iteration + 1, narrow_bits(bits)
            )
            if (iteration + 1) % CHECKPOINT_INTERVAL == 0:
                checkpoints.append(signature)
        groups.append(checkpoints)
    return groups


def expected_signature():
    signature = SIGNATURE_SEED
    checkpoints_per_group = ITERATIONS // CHECKPOINT_INTERVAL
    for seed_index, checkpoints in enumerate(checkpoint_groups()):
        base = seed_index * checkpoints_per_group
        for checkpoint_index, checkpoint in enumerate(checkpoints):
            signature = signature_step(
                signature, base + checkpoint_index + 1, checkpoint
            )
    return signature


def emit_u32_array(name, values):
    print(f"static const abi_u32 {name}[{len(values)}] = {{")
    for index in range(0, len(values), 4):
        line = ", ".join(
            f"0x{value:08x}UL" for value in values[index:index + 4]
        )
        suffix = "," if index + 4 < len(values) else ""
        print(f"  {line}{suffix}")
    print("};")


def emit_corpus():
    checkpoints = [
        checkpoint
        for group in checkpoint_groups()
        for checkpoint in group
    ]
    print("#ifndef SEEDED_F64_TO_F32_CORPUS_INC")
    print("#define SEEDED_F64_TO_F32_CORPUS_INC")
    print()
    print(f"#define ABI_F64_TO_F32_SUITE_ID {SUITE_ID}U")
    print(f"#define ABI_F64_TO_F32_ITERATIONS {ITERATIONS}U")
    print(f"#define ABI_F64_TO_F32_SEED_COUNT {len(SEEDS)}U")
    print(f"#define ABI_F64_TO_F32_CHECKPOINT_COUNT {len(checkpoints)}U")
    print(f"#define ABI_F64_TO_F32_RESULT_COUNT "
          f"{len(SEEDS) * ITERATIONS}UL")
    print(
        "#define ABI_F64_TO_F32_CHECKPOINT_INTERVAL "
        f"{CHECKPOINT_INTERVAL}U"
    )
    print(
        "#define ABI_F64_TO_F32_CHECKPOINTS_PER_GROUP "
        f"{ITERATIONS // CHECKPOINT_INTERVAL}U"
    )
    print(f"#define ABI_F64_TO_F32_EDGE_COUNT {len(EDGES)}U")
    print(
        "#define ABI_F64_TO_F32_GROUP_SIGNATURE_SEED "
        f"0x{GROUP_SIGNATURE_SEED:08x}UL"
    )
    print()
    emit_u32_array("abi_f64_to_f32_seed_hi", [seed >> 32 for seed in SEEDS])
    emit_u32_array(
        "abi_f64_to_f32_seed_lo", [seed & MASK32 for seed in SEEDS]
    )
    emit_u32_array("abi_f64_to_f32_edge_hi", [edge >> 32 for edge in EDGES])
    emit_u32_array(
        "abi_f64_to_f32_edge_lo", [edge & MASK32 for edge in EDGES]
    )
    emit_u32_array("abi_f64_to_f32_expected", checkpoints)
    print()
    print("#endif")


def main():
    global ITERATIONS, CHECKPOINT_INTERVAL, SEEDS, SUITE_ID

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "mode",
        choices=("corpus", "signature", "check-count", "result-count"),
    )
    parser.add_argument("--iterations", type=int, default=ITERATIONS)
    parser.add_argument(
        "--checkpoint-interval", type=int, default=CHECKPOINT_INTERVAL
    )
    parser.add_argument("--suite-id", type=int, default=SUITE_ID)
    parser.add_argument(
        "--seed", action="append", type=lambda value: int(value, 0), default=[]
    )
    args = parser.parse_args()

    seeds = tuple(args.seed) if args.seed else SEEDS
    if not 1 <= args.iterations <= 32767:
        parser.error("--iterations must be in 1..32767")
    if (args.checkpoint_interval <= 0 or
            args.checkpoint_interval & (args.checkpoint_interval - 1)):
        parser.error("--checkpoint-interval must be a power of two")
    if args.iterations % args.checkpoint_interval:
        parser.error("--iterations must be divisible by --checkpoint-interval")
    if not seeds or any(not 0 <= seed <= MASK64 for seed in seeds):
        parser.error("each --seed must be an unsigned 64-bit value")
    checkpoint_count = (
        len(seeds) * args.iterations // args.checkpoint_interval
    )
    if checkpoint_count > 4095:
        parser.error("checkpoint table must fit one 16 KiB far object")
    if not 0 <= args.suite_id <= 65535:
        parser.error("--suite-id must fit unsigned 16 bits")

    ITERATIONS = args.iterations
    CHECKPOINT_INTERVAL = args.checkpoint_interval
    SEEDS = seeds
    SUITE_ID = args.suite_id

    if args.mode == "corpus":
        emit_corpus()
    elif args.mode == "signature":
        print(expected_signature())
    elif args.mode == "check-count":
        print(checkpoint_count)
    else:
        print(len(SEEDS) * ITERATIONS)


if __name__ == "__main__":
    main()
