#!/usr/bin/env python3
import argparse
from pathlib import Path

MASK16 = 0xFFFF
MASK32 = 0xFFFFFFFF


def u16(value):
    return value & MASK16


def u32(value):
    return value & MASK32


def s8(value):
    value &= 0xFF
    return value - 0x100 if value & 0x80 else value


def u8(value):
    return value & 0xFF


def s16(value):
    value &= MASK16
    return value - 0x10000 if value & 0x8000 else value


def rol(value, count):
    value = u32(value)
    return u32((value << count) | (value >> (32 - count)))


def ror(value, count):
    value = u32(value)
    return u32((value >> count) | (value << (32 - count)))


def signature_step(signature, case_id, actual):
    tag = u32((case_id << 16) | case_id)
    return u32(rol(signature, 5) ^ actual ^ tag)


def expected(vector):
    operation, x, sx, y, aux, sc, uc, tail = vector
    x = u32(x)
    y = u32(y)
    if operation == 0:
        return u32(u32(x + y) - y)
    if operation == 1:
        return u32((x ^ y) ^ y)
    if operation == 2:
        count = ((aux ^ tail) % 31) + 1
        return ror(rol(x, count), count)
    if operation == 3:
        assert y != 0
        return u32((x // y) * y + x % y)
    if operation == 4:
        return u32(~(x & y))
    if operation == 5:
        value = 1 if x < y else 0
        return value | (value << 16)
    if operation == 6:
        side_effect = u16(tail + (3 if aux & 1 else 5))
        return u32((side_effect << 16) | side_effect)
    if operation == 7:
        return u32(x ^ rol(y, 1))
    if operation == 8:
        third = u32((aux << 16) | tail)
        return u32(x & (y | third))
    if operation == 9:
        count = ((aux ^ tail) % 31) + 1
        mask = (1 << count) - 1
        return u32(((x >> count) << count) | (x & mask))
    if operation in (10, 12):
        return u32(s8(sc))
    if operation in (11, 13):
        return u8(uc)
    if operation == 14:
        assert -128 <= sx <= 127
        return u32(s8(sx))
    if operation == 15:
        return u8(x)
    if operation == 16:
        assert -32768 <= sx <= 32767
        return u32(s16(sx))
    raise AssertionError(operation)


VECTORS = [
    (0, 0x00000000, 0, 0xFFFFFFFF, 0, -128, 255, 0),
    (0, 0xDEADBEEF, -1, 0x81234567, 1, 127, 0, 0xFFFF),
    (1, 0xFFFFFFFF, 0, 0xAAAAAAAA, 0, 0, 0, 0),
    (1, 0x13579BDF, 0, 0x2468ACE0, 0, 0, 0, 0),
    (2, 0x80000001, 0, 0, 0, 0, 0, 0),
    (2, 0xDEADBEEF, 0, 0, 30, 0, 0, 0),
    (3, 0xFFFFFFFF, 0, 1, 0, 0, 0, 0),
    (3, 0xDEADBEEF, 0, 0x13579BDF, 0, 0, 0, 0),
    (4, 0x00000000, 0, 0xFFFFFFFF, 0, 0, 0, 0),
    (4, 0xA55A5AA5, 0, 0x0F0FF0F0, 0, 0, 0, 0),
    (5, 0x12345678, 0, 0x12345678, 0, 0, 0, 0),
    (5, 0x00000000, 0, 0xFFFFFFFF, 0, 0, 0, 0),
    (5, 0xFFFFFFFF, 0, 0x00000000, 0, 0, 0, 0),
    (6, 0xDEADBEEF, 0, 0x12345678, 1, 0, 0, 0x1357),
    (6, 0xDEADBEEF, 0, 0x12345678, 0, 0, 0, 0x7FFF),
    (7, 0x00000000, 0, 0x80000001, 0, 0, 0, 0),
    (7, 0x13579BDF, 0, 0x2468ACE0, 0, 0, 0, 0),
    (8, 0xFFFFFFFF, 0, 0x00000000, 0xA55A, 0, 0, 0x5AA5),
    (8, 0x13579BDF, 0, 0x00FF00FF, 0x2468, 0, 0, 0xACE0),
    (9, 0x80000001, 0, 0, 0, 0, 0, 0),
    (9, 0xDEADBEEF, 0, 0, 30, 0, 0, 0),
    (10, 0, 0, 0, 0, -128, 0, 0),
    (10, 0, 0, 0, 0, -1, 0, 0),
    (10, 0, 0, 0, 0, 0, 0, 0),
    (10, 0, 0, 0, 0, 127, 0, 0),
    (11, 0, 0, 0, 0, 0, 0, 0),
    (11, 0, 0, 0, 0, 0, 127, 0),
    (11, 0, 0, 0, 0, 0, 128, 0),
    (11, 0, 0, 0, 0, 0, 255, 0),
    (12, 0, 0, 0, 0, -128, 0, 0),
    (12, 0, 0, 0, 0, 127, 0, 0),
    (13, 0, 0, 0, 0, 0, 0, 0),
    (13, 0, 0, 0, 0, 0, 255, 0),
    (14, 0, -128, 0, 0, 0, 0, 0),
    (14, 0, -1, 0, 0, 0, 0, 0),
    (14, 0, 0, 0, 0, 0, 0, 0),
    (14, 0, 127, 0, 0, 0, 0, 0),
    (15, 0x00000000, 0, 0, 0, 0, 0, 0),
    (15, 0x123456FF, 0, 0, 0, 0, 0, 0),
    (16, 0, -32768, 0, 0, 0, 0, 0),
    (16, 0, -1, 0, 0, 0, 0, 0),
    (16, 0, 0, 0, 0, 0, 0, 0),
    (16, 0, 32767, 0, 0, 0, 0, 0),
]


def expected_signature():
    signature = 0x16600141
    for case_id, vector in enumerate(VECTORS, 1):
        signature = signature_step(signature, case_id, expected(vector))
    return signature


def signed_literal(value):
    return f"{value}L" if value >= 0 else f"({value}L)"


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--signature", action="store_true")
    args = parser.parse_args()
    if args.signature:
        print(expected_signature())
        return

    lines = [
        "#ifndef C166_METAMORPHIC_CONVERSION_VECTORS_INC",
        "#define C166_METAMORPHIC_CONVERSION_VECTORS_INC",
        "",
        "#define C166_METAMORPHIC_VECTORS(X) \\",
    ]
    for case_id, vector in enumerate(VECTORS, 1):
        operation, x, sx, y, aux, sc, uc, tail = vector
        suffix = " \\" if case_id != len(VECTORS) else ""
        lines.append(
            f"  X({case_id}, {operation}U, 0x{x:08x}UL, "
            f"{signed_literal(sx)}, 0x{y:08x}UL, 0x{aux:04x}U, "
            f"{sc}, {uc}U, 0x{tail:04x}U, "
            f"0x{expected(vector):08x}UL){suffix}"
        )
    lines.extend([
        "",
        f"#define C166_METAMORPHIC_VECTOR_COUNT {len(VECTORS)}U",
        f"#define C166_METAMORPHIC_EXPECTED_SIGNATURE "
        f"0x{expected_signature():08x}UL",
        "",
        "#endif",
        "",
    ])
    Path(__file__).with_name("vectors.inc").write_text("\n".join(lines))


if __name__ == "__main__":
    main()
