"""Reference input compiler. Instructions are ('inc',r) and ('dec',r,target). At zero, dec advances. At a positive value it subtracts one and jumps. Leaving the program returns the selected register. Compiled words can be huge. """ B = "lmlr" INVERTER = "bbrrr" def synth(inputs, outputs): """Iterative bit-packed implementation of the running-XOR stream compiler (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 clocks(machine, pc, registers, output): """Compile a finite register program, its return site, and all drain loops.""" if not registers or min(registers) < 0 or not 0 <= output < len(registers): raise ValueError("expected natural registers and a valid output register") 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 not 0 <= c < len(registers): raise ValueError("bad register") if op == "inc" and not args: branch = (target(j + 1), (c,)) sites.append((len(registers), branch, branch)) # fresh, permanently zero elif op == "dec" and len(args) == 1: sites.append((c, (target(args[0]), ()), (target(j + 1), ()))) else: raise ValueError("bad register instruction") # The first visit to report is the unique return boundary. report = end first_drain = report + 1 sites.append((output, (first_drain, ()), (first_drain, ()))) for reg in range(len(registers)): j = first_drain + reg sites.append((reg, (j, ()), (j + 1, ()))) 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, en(report), data(report) def to_restart(machine, pc, registers, output=0): matrix, halt, clocks0, terminal, entry, result = clocks(machine, pc, registers, output) n = len(matrix) # Temporarily number the strobe last, then permute physical cell order. strobe = 1 + 2*n 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)) commands.extend((("+", strobe), ("-", strobe))) 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)) initial = [1, *(v for c in clocks0 for v in (1, c)), 0] front = [strobe, value(entry), value(result)] order = front + [i for i in range(len(initial)) if i not in front] new_index = {old: new for new, old in enumerate(order)} return [(op, new_index[i]) for op, i in commands], [initial[i] for i in order] def encode_registers(program, registers, output=0, pc=0): """Compile a register program and initial values to an ordinary tag word.""" instructions, initial = to_restart(program, pc, registers, output) return encode_restart(instructions, initial)