File size: 4,636 Bytes
7d56523
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
"""The brainphoque machine: run a program and get its output.

This file is the specification of the machine used for the brainphoque-minimal-14 dataset.
`run_reference` is a direct, readable implementation; `run` uses the C version in bfrun.c
when it has been built (cc -O2 -shared -fPIC -o libbfrun.so bfrun.c) and falls back to the
reference otherwise. Both return identical results.

Machine: a circular tape of 256 byte cells (all 0 at the start) and one head. Every symbol,
macros included, costs one step. A run completes if it halts (runs off the end of the program)
or prints its 4,095th byte within 65,536 steps; otherwise it has no output. The output is the
first 4,095 printed bytes; outputs are compared after removing trailing zero bytes.
"""
import ctypes, os

SYMBOLS = "<>+-[].ZRLNCGHWVX"
TAPE, T, BUDGET = 256, 4095, 65536
HALT, FULL, CUT = "halts", "prints 4095 bytes", "cut"

def run_reference(program):
    """Return (status, steps, output) for a program string; output has trailing zeros removed."""
    match, stack = {}, []
    for i, c in enumerate(program):                      # unmatched brackets are no-ops
        if c == '[': stack.append(i)
        elif c == ']' and stack: j = stack.pop(); match[i] = j; match[j] = i
    tape, out = bytearray(TAPE), bytearray()
    pc = p = steps = 0
    def done(status):
        o = bytes(out)
        return status, steps, o.rstrip(b'\0')
    while pc < len(program):
        if steps >= BUDGET: return CUT, steps, b''
        steps += 1
        c = program[pc]
        if c == '+': tape[p] = (tape[p] + 1) & 255
        elif c == '-': tape[p] = (tape[p] - 1) & 255
        elif c == '>': p = (p + 1) % TAPE
        elif c == '<': p = (p - 1) % TAPE
        elif c == '[':
            if pc in match and tape[p] == 0: pc = match[pc]
        elif c == ']':
            if pc in match and tape[p] != 0: pc = match[pc]
        elif c == '.':
            out.append(tape[p])
            if len(out) == T: return done(FULL)
        elif c == 'Z': tape[p] = 0                                             # [-]
        elif c == 'X': tape[p] = 16
        elif c in 'RLNC':
            x = tape[p]; tape[p] = 0
            if c == 'R': tape[(p + 1) % TAPE] = (tape[(p + 1) % TAPE] + x) & 255        # [->+<]
            elif c == 'L': tape[(p + 1) % TAPE] = (tape[(p + 1) % TAPE] + 3 * x) & 255  # [->+++<]
            elif c == 'N': tape[(p - 1) % TAPE] = (tape[(p - 1) % TAPE] - x) & 255      # [-<->]
            else:                                                              # [->+>+<<]
                tape[(p + 1) % TAPE] = (tape[(p + 1) % TAPE] + x) & 255
                tape[(p + 2) % TAPE] = (tape[(p + 2) % TAPE] + x) & 255
        elif c in 'GH':                                    # [>] / [<]: move to the nearest zero cell
            d = 1 if c == 'G' else -1
            for _ in range(TAPE):
                if tape[p] == 0: break
                p = (p + d) % TAPE
            if tape[p] != 0: return CUT, steps, b''        # no zero cell: never finishes
        elif c == 'W':                                     # if nonzero: clear, add 1 to the right
            if tape[p]: tape[p] = 0; tape[(p + 1) % TAPE] = (tape[(p + 1) % TAPE] + 1) & 255
        elif c == 'V':                                     # [.>]: print and move right until a zero
            while tape[p]:
                out.append(tape[p]); p = (p + 1) % TAPE
                if len(out) == T: return done(FULL)
        else:
            raise ValueError(f"bad symbol {c!r}")
        pc += 1
    return done(HALT)

_lib = None
def _load():
    global _lib
    if _lib is None:
        path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'libbfrun.so')
        if os.path.exists(path):
            _lib = ctypes.CDLL(path)
            _lib.bf_run.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)]
            _lib.bf_run.restype = ctypes.c_int
        else:
            _lib = False
    return _lib

def run(program):
    """Same as run_reference, using the C implementation when libbfrun.so is present."""
    lib = _load()
    if not lib: return run_reference(program)
    buf = ctypes.create_string_buffer(T); n = ctypes.c_int(); s = ctypes.c_int()
    r = lib.bf_run(program.encode(), buf, ctypes.byref(n), ctypes.byref(s))
    if r < 0: raise ValueError(f"bad program {program!r}")
    return (CUT, HALT, FULL)[r], s.value, buf.raw[:n.value].rstrip(b'\0') if r else b''

def padded(output):
    """The full 4,095-byte output (zero-padded), as used for training."""
    return output + bytes(T - len(output))