|
| 1 | +# -*- coding: UTF-8 -*- |
| 2 | +"""Malbolge Codec - Malbolge content encoding. |
| 3 | +
|
| 4 | +Malbolge is an esoteric programming language created by Ben Olmstead in 1998, designed to be as difficult to program in |
| 5 | + as possible. It runs on a ternary virtual machine with 59049 words of 10 trits, holding both the code and the data, and |
| 6 | + three registers (A, the accumulator, C, the code pointer, and D, the data pointer). The instruction executed depends on |
| 7 | + the character at C and on its position ((C + [C]) % 94): "j" (D = [D]), "i" (C = [D]), "*" (A = [D] = [D] rotated to |
| 8 | + the right), "p" (A = [D] = crazy operation of A and [D]), "<" (output A modulo 256), "/" (input to A), "v" (stop) and |
| 9 | + "o" (nop), the executed character being then enciphered. Encoding generates a program that prints the text (as UTF-8), |
| 10 | + while decoding runs the program and returns its output. |
| 11 | +
|
| 12 | +The program is run as with the reference interpreter ("<" being the output, as in the reference interpreter, and not |
| 13 | + the input as in the specification), the cases left undefined by the reference interpreter being handled as in the |
| 14 | + specification: executing a character that is not graphic ASCII ends the program and a modified cell that is no longer |
| 15 | + graphic ASCII is not enciphered. No input is available ("/" gives the end of file, 59048). The program must have at |
| 16 | + least two instructions ; whitespace is ignored and invalid characters are only accepted (and skipped) with a non-strict |
| 17 | + errors handling. A program that does not halt within 1000 steps per instruction (with a minimum of 1 million) is |
| 18 | + stopped. |
| 19 | +
|
| 20 | +Encoding searches, for each byte, the shortest sequence of "o", "p", "*" and "j" that sets A to this byte (modulo 256) |
| 21 | + before printing it with "<", "j" moving the data pointer back to cells already executed (holding values written by |
| 22 | + former instructions) so that all the bytes can be reached. |
| 23 | +
|
| 24 | +This codec: |
| 25 | +- en/decodes strings from str to str |
| 26 | +- en/decodes strings from bytes to bytes |
| 27 | +- decodes file content to str (read) |
| 28 | +- encodes file content from str to bytes (write) |
| 29 | +
|
| 30 | +Reference: https://www.lscheffer.com/malbolge_spec.html |
| 31 | + https://esolangs.org/wiki/Malbolge |
| 32 | +""" |
| 33 | +from ._brainfuck import MIN_STEPS, STEPS_PER_COMMAND |
| 34 | +from ..__common__ import * |
| 35 | + |
| 36 | + |
| 37 | +__examples__ = { |
| 38 | + 'enc(malbolge|mb)': {'': "DP", 'A': ">CB;@?>=<;4XE", 'Hi': "DCBA@?>=6;:981U543210/.-&%*#G4"}, |
| 39 | + 'dec(malbolge)': { |
| 40 | + # Hello World program from Wikipedia and program printing 42 from the Esoteric File Archive |
| 41 | + "(=<`#9]~6ZY32Vx/4Rs+0No-&Jk)\"Fh}|Bcy?`=*z]Kw%oG4UUS0/@-ejc(:'8dc": "Hello World!", |
| 42 | + "'&%$#\"!76543210/43,P0).'&%I6": "42", |
| 43 | + # whitespace is ignored |
| 44 | + "D\n P ": "", |
| 45 | + # less than two instructions, invalid characters |
| 46 | + "Q": None, |
| 47 | + "D\xe9P": None, |
| 48 | + "DQ": None, |
| 49 | + }, |
| 50 | + 'enc-dec(malbolge)': ["", "Hello World!", "@random{64}", "Caf\xe9, \xf1and\xfa & 10\u20ac", "\x00a\x00"], |
| 51 | +} |
| 52 | +__guess__ = ["malbolge"] |
| 53 | + |
| 54 | + |
| 55 | +SIZE = 3 ** 10 |
| 56 | +XLAT1 = "+b(29e*j1VMEKLyC})8&m#~W>qxdRp0wkrUo[D7,XTcA\"lI.v%{gJh4G\\-=O@5`_3i<?Z';FNQuY]szf$!BS/|t:Pn6^Ha" |
| 57 | +XLAT2 = "5z]&gqtyfr$(we4{WP)H-Zn,[%\\3dL+Q;>U!pJS72FhOA1CB6v^=I_0/8|jsb9m<.TVac`uY*MK'X~xDl}REokN:#?G\"i@" |
| 58 | +# crazy operation on trits, as CRAZY[trit of [D]][trit of A], then on pairs of trits |
| 59 | +CRAZY = [[1, 0, 0], [1, 0, 2], [2, 2, 1]] |
| 60 | +_CRAZY9 = [[CRAZY[d // 3][a // 3] * 3 + CRAZY[d % 3][a % 3] for a in range(9)] for d in range(9)] |
| 61 | + |
| 62 | + |
| 63 | +def crazy(a, d): |
| 64 | + """ Tritwise crazy operation of A and [D]. """ |
| 65 | + r, p = 0, 1 |
| 66 | + for _ in range(5): |
| 67 | + r += _CRAZY9[d % 9][a % 9] * p |
| 68 | + a, d, p = a // 9, d // 9, p * 9 |
| 69 | + return r |
| 70 | + |
| 71 | + |
| 72 | +def rotr(v): |
| 73 | + """ Rotate a word to the right by one trit. """ |
| 74 | + return v // 3 + v % 3 * 3 ** 9 |
| 75 | + |
| 76 | + |
| 77 | +# values (character codes) of the instructions at each position (modulo 94) |
| 78 | +_VALUES = {i: [33 + (XLAT1.index(i) - k) % 94 for k in range(94)] for i in "ji*p</vo"} |
| 79 | + |
| 80 | + |
| 81 | +def _value(i, instruction): |
| 82 | + """ Value (character code) of the given instruction at the given position. """ |
| 83 | + return _VALUES[instruction][i % 94] |
| 84 | + |
| 85 | + |
| 86 | +def _step(state, instruction, c, cells): |
| 87 | + """ Simulate an instruction at position c of the program being encoded, from the state (A, D, cells modified while |
| 88 | + searching), cells holding the values of the executed part of the program ; the data pointer never goes ahead |
| 89 | + of the code pointer, as the next cells are not known yet. """ |
| 90 | + a, d, new = state |
| 91 | + v = _value(c, instruction) |
| 92 | + get = lambda x: v if x == c else new.get(x, cells.get(x)) |
| 93 | + new = dict(new) |
| 94 | + if instruction == "j": |
| 95 | + if (d := get(d)) > c: |
| 96 | + return |
| 97 | + elif instruction == "*": |
| 98 | + a = new[d] = rotr(get(d)) |
| 99 | + elif instruction == "p": |
| 100 | + a = new[d] = crazy(a, get(d)) |
| 101 | + # the executed character is enciphered (or the value written in its cell, if graphic ASCII) |
| 102 | + w = new.get(c, v) |
| 103 | + new[c] = ord(XLAT2[w - 33]) if 33 <= w <= 126 else w |
| 104 | + return a, d + 1, new |
| 105 | + |
| 106 | + |
| 107 | +def malbolge_run(program, max_steps=None): |
| 108 | + """ Run a Malbolge program (as a list of character codes) and return its output as bytes. |
| 109 | +
|
| 110 | + :param program: list of the values of the instructions |
| 111 | + :param max_steps: maximum number of executed instructions, for stopping programs that do not halt (by default, |
| 112 | + 1000 per instruction, with a minimum of 1 million) |
| 113 | + """ |
| 114 | + # the remaining memory is filled with the crazy operation of the previous word and of the second previous one, |
| 115 | + # lazily (up to the highest address used), from the last two initial words |
| 116 | + mem, (x, y) = list(program), program[-2:] |
| 117 | + max_steps = max_steps or max(MIN_STEPS, STEPS_PER_COMMAND * len(program)) |
| 118 | + a, c, d, out = 0, 0, 0, bytearray() |
| 119 | + for _ in range(max_steps): |
| 120 | + while len(mem) <= max(c, d): |
| 121 | + x, y = y, crazy(y, x) |
| 122 | + mem.append(y) |
| 123 | + if not 33 <= mem[c] <= 126: |
| 124 | + # a character that is not graphic ASCII ends the program |
| 125 | + return bytes(out) |
| 126 | + i = XLAT1[(mem[c] - 33 + c) % 94] |
| 127 | + if i == "j": |
| 128 | + d = mem[d] |
| 129 | + elif i == "i": |
| 130 | + c = mem[d] |
| 131 | + elif i == "*": |
| 132 | + a = mem[d] = rotr(mem[d]) |
| 133 | + elif i == "p": |
| 134 | + a = mem[d] = crazy(a, mem[d]) |
| 135 | + elif i == "<": |
| 136 | + out.append(a % 256) |
| 137 | + elif i == "/": |
| 138 | + # no input is available, hence the end of file |
| 139 | + a = SIZE - 1 |
| 140 | + elif i == "v": |
| 141 | + return bytes(out) |
| 142 | + if 33 <= mem[c] <= 126: |
| 143 | + mem[c] = ord(XLAT2[mem[c] - 33]) |
| 144 | + c, d = (c + 1) % SIZE, (d + 1) % SIZE |
| 145 | + raise ValueError(f"program did not halt within {max_steps} steps") |
| 146 | + |
| 147 | + |
| 148 | +def malbolge_encode(text, errors="strict"): |
| 149 | + # for each byte, a breadth-first search finds the shortest sequence of instructions setting A to this byte (modulo |
| 150 | + # 256), keeping one state per value of A and D at each depth |
| 151 | + r, cells, state = "", {}, (0, 0, {}) |
| 152 | + for b in text.encode("utf-8"): |
| 153 | + layer, found = {state[:2]: (state, "")}, (state, "") if state[0] % 256 == b else None |
| 154 | + while found is None: |
| 155 | + c, new = len(r) + len(next(iter(layer.values()))[1]), {} |
| 156 | + for st, path in layer.values(): |
| 157 | + for i in "opj*": |
| 158 | + if (st2 := _step(st, i, c, cells)) is not None and st2[:2] not in new: |
| 159 | + new[st2[:2]] = (st2, path + i) |
| 160 | + # stop as soon as A holds the byte |
| 161 | + if st2[0] % 256 == b: |
| 162 | + found = new[st2[:2]] |
| 163 | + break |
| 164 | + if found: |
| 165 | + break |
| 166 | + layer = new |
| 167 | + state, path = found |
| 168 | + for i in path + "<": |
| 169 | + r += chr(_value(len(r), i)) |
| 170 | + a, d, new = _step(state, "<", len(r) - 1, cells) |
| 171 | + cells.update(new) |
| 172 | + state = (a, d, {}) |
| 173 | + # the program has at least two instructions |
| 174 | + r = r or chr(_value(0, "o")) |
| 175 | + if len(r) >= SIZE: |
| 176 | + raise MalbolgeEncodeError("'malbolge' codec can't encode: the text is too long") |
| 177 | + return (r := r + chr(_value(len(r), "v"))), len(text) |
| 178 | + |
| 179 | + |
| 180 | +def malbolge_decode(text, errors="strict"): |
| 181 | + _h, program = handle_error("malbolge", errors, decode=True, kind="instruction"), [] |
| 182 | + for k, c in enumerate(ensure_str(text)): |
| 183 | + if c.isspace(): |
| 184 | + continue |
| 185 | + if not 33 <= ord(c) <= 126 or XLAT1[(ord(c) - 33 + len(program)) % 94] not in "ji*p</vo": |
| 186 | + # with a non-strict errors handling, invalid characters are skipped |
| 187 | + _h(c, k) |
| 188 | + continue |
| 189 | + program.append(ord(c)) |
| 190 | + if len(program) < 2: |
| 191 | + raise MalbolgeDecodeError("'malbolge' codec can't decode: the program must have at least two instructions") |
| 192 | + if len(program) > SIZE: |
| 193 | + raise MalbolgeDecodeError("'malbolge' codec can't decode: the program is too long") |
| 194 | + return (r := ensure_str(malbolge_run(program))), len(r) |
| 195 | + |
| 196 | + |
| 197 | +add("malbolge", malbolge_encode, malbolge_decode, r"^(?:malbolge|mb)$", printables_rate=1., |
| 198 | + expansion_factor=(8., .1)) |
0 commit comments