"""Reference compiler for the fixed tag table in the accompanying paper. Commands of a restart program are pairs (sign, zero-based cell index). CM2 instructions are ("inc", register) or ("dec", register, positive_target). """ from collections import deque RULES = dict(a="rrd", b="ahaa", d="bbrrr", e="g", f="r", g="ij", i="ehee", j="rhke", k="frgg", l="uuff", m="v", u="pp", v="pprprprprprprprp", p="lmlr", h="h", r="") B = "lmlr" INVERTER = "bbrrr" def synth(inputs, outputs): """Iterative bit-packed implementation of Tag16.synth (time increases to the right).""" n = len(inputs) if n != len(outputs): raise ValueError("unequal stream lengths") packed = int("".join(map(str, reversed(outputs))), 2) if n else 0 heads = [] for u in inputs: heads.append((u, packed & 1)) packed ^= packed >> 1 # low remaining bits are successive differences state = 0 for size, (u, y) in enumerate(reversed(heads)): carry = state >> (size - 1) if size else u state = ((state ^ (state << 1) ^ u) & ((1 << size) - 1)) | ((carry ^ y) << size) return [(state >> i) & 1 for i in range(n)] def encode_restart(commands, values): """Produce a literal finite tag word. Space can be exponential in initial cell values.""" q = len(values) if q < 1 or any(x < 0 for x in values): raise ValueError("expected a nonempty vector of natural numbers") count = q + 1 # includes the dedicated halt counter widths = [[] for _ in range(count + 2)] # signals at section edges def row(start, counter_lanes, end): for signal, bit in zip(widths, (start, *counter_lanes, end), strict=True): signal.append(bit) row(1, [1] * count, 0) row(0, [0] * count, 0) for sign, cell in commands: if sign not in ("+", "-") or not 0 <= cell < q: raise ValueError("invalid source instruction") first, second = [1] * count, [0] * count if sign == "+": first[cell] = 0 else: second[cell] = 1 row(0, first, 0) row(0, second, 0) row(0, [1] * count, 0) row(0, [0] * q + [1], 1) # A fictitious ordinary update fixes the terminal suffix's Command width. row(0, [0] * count, 0) row(0, [0] * count, 0) # even stream length residues = [1980] + [1024] * (q - 1) + [2046, 2025] word = [] initial = [*values, 0] for j, residue in enumerate(residues): flags = synth(widths[j], widths[j + 1]) section = "".join("ij" + INVERTER * a for a in flags) pad = (residue - len(flags) - sum(flags)) % 2048 assert pad % 2 == 0 word.append(section + INVERTER * pad) if j < count: word.append(B * (1 << (2 * initial[j] + 1))) return "".join(word)[1:] # virtual Command word starts with offset 1 def literal(word, limit): queue = deque(word) for steps in range(limit + 1): if len(queue) < 2: return steps, "".join(queue) if steps == limit: break first = queue.popleft() queue.popleft() queue.extend(RULES[first]) raise RuntimeError("literal step budget exhausted") def clocks(machine, pc, registers): """Compile CM2 to a unique-trigger clock network, including two drain loops.""" if len(registers) != 2 or min(registers) < 0: raise ValueError("expected two natural-number registers") end = len(machine) def target(p): return p if 0 <= p < end else end sites = [] # tested register, positive (target,adds), zero (target,adds) for j, ins in enumerate(machine): op, c, *args = ins if c not in (0, 1): raise ValueError("bad CM2 register") if op == "inc" and not args: branch = (target(j + 1), (c,)) sites.append((2, branch, branch)) # register 2 is permanently zero elif op == "dec" and len(args) == 1: sites.append((c, (target(args[0]), ()), (target(j + 1), ()))) else: raise ValueError("bad CM2 instruction") sites += [(0, (end, ()), (end + 1, ())), (1, (end + 1, ()), (end + 2, ()))] n = len(sites) halt = n en = lambda j: j race = lambda j: n + 1 + j data = lambda j: 2 * n + 1 + j size = 3 * n + 1 matrix = [[0] * size for _ in range(size)] for j, (reg, positive, zero) in enumerate(sites): for k in range(n + 1): matrix[en(j)][en(k)] = 7 if k == j else 3 for k in range(n): matrix[en(j)][race(k)] = 2 if k == j else 6 matrix[en(j)][data(k)] = 0 if k == j else 2 for is_positive, (goto, adds) in [(True, positive), (False, zero)]: line = matrix[race(j) if is_positive else data(j)] for k in range(n + 1): line[en(k)] = 0 if k == goto else 4 for k, (other, _, _) in enumerate(sites): line[race(k)] = 5 if k == j else 1 if is_positive: base = 3 if k != j and reg == other else 5 else: base = 7 if k == j else 5 line[data(k)] = base + 2 * adds.count(other) values = (*registers, 0) initial = [1 if k == target(pc) else 5 for k in range(n + 1)] initial += [2] * n + [2 * values[r] + 3 for r, _, _ in sites] terminal = [0 if k == halt else 4 for k in range(n + 1)] + [1] * n + [2] * n return matrix, halt, initial, terminal def to_restart(machine, pc, registers): matrix, halt, clocks0, terminal = clocks(machine, pc, registers) n = len(matrix) marker = 0 z = lambda j: 1 + 2 * j value = lambda j: 2 + 2 * j commands = [("-", marker)] for i, line in enumerate(matrix): increments = [value(j) for j in range(n) for _ in range((2 if i == halt else line[j]) - int(i == j))] if i == halt: increments.extend([marker, marker]) commands.extend(("+", cell) for cell in increments) commands.extend([("-", z(i)), ("+", z(i))]) commands.extend(("-", cell) for cell in reversed(increments)) commands.extend(("-", value(i)) for i in range(n)) for i in range(n): commands.extend([("-", z(i)), ("-", value(i)), ("+", value(i)), ("+", z(i))]) commands.append(("-", marker)) for i in range(n): commands.append(("-", z(i))) commands.extend([("-", value(i))] * (terminal[i] + 1)) return commands, [1, *(v for c in clocks0 for v in (1, c))] def encode_cm2(machine, pc, registers): return encode_restart(*to_restart(machine, pc, registers)) def interpret(commands, initial, limit): cells = initial.copy() pc = 0 for steps in range(limit + 1): if pc == len(commands): return steps, cells if steps == limit: break sign, i = commands[pc] pc += 1 if sign == "+": cells[i] += 1 elif cells[i]: cells[i] -= 1 else: cells[i] = 1 pc = 0 raise RuntimeError("source step budget exhausted") if __name__ == "__main__": # Reaches a failed decrement, restarts, then perfect-halts. program = [("+", 0), ("-", 1), ("-", 0), ("-", 0)] result = literal(encode_restart(program, [0, 0]), 2_000_000) assert len(result[1]) < 2 print("Natural tag halt (literal steps, terminal word):", result) # Both branches of dec and a nonzero input; both registers are drained. cm = [("dec", 0, 0), ("inc", 1)] steps, final = interpret(*to_restart(cm, 0, (2, 1)), limit=4_000_000) assert not any(final) print("Compiled CM2 example (restart instructions, final sum):", steps, sum(final))