Skip to content

Commit 7f05da9

Browse files
committed
Added codec: malbolge
1 parent f1ab468 commit 7f05da9

5 files changed

Lines changed: 236 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,7 @@ This category also contains `ascii85`, `adobe`, `[x]btoa`, `zeromq` with the `ba
395395
- [X] `brainfuck`: well-known esoteric programming language (encoding generates a program printing the text)
396396
- [X] `cow`: esoteric language made of variations of "moo" (Brainfuck-like, with a register and integer output)
397397
- [X] `lolcode`: esoteric language inspired by lolcats (encoding generates a program printing the text), also with lowercase keywords
398+
- [X] `malbolge`: esoteric language designed to be as difficult to program in as possible (encoding generates a program printing the text)
398399
- [X] `ook`: Brainfuck derivative for orang-utans (`Ook.`, `Ook?` and `Ook!`), also in its short form
399400
- [X] `pikalang`: Brainfuck derivative using Pikachu's vocabulary
400401

‎docs/pages/enc/esoteric.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,27 @@ COW is made of 12 variations of the word "moo". Its memory is a tape of integer
8383

8484
-----
8585

86+
### Malbolge
87+
88+
[Malbolge](https://esolangs.org/wiki/Malbolge) is an esoteric programming language designed to be as difficult to program in as possible. It runs on a ternary virtual machine with 59049 words of 10 trits, holding both the code and the data, and three registers (`A`, the accumulator, `C`, the code pointer, and `D`, the data pointer). The instruction executed depends on the character at `C` and on its position, among `j` (`D = [D]`), `i` (`C = [D]`), `*` (rotate `[D]` to the right), `p` ("crazy" tritwise operation of `A` and `[D]`), `<` (output `A`), `/` (input to `A`), `v` (stop) and `o` (nop), and the executed character is then enciphered. Encoding generates a program that prints the text (as UTF-8), searching for each byte the shortest sequence of instructions setting `A` to it, while decoding runs the program and returns its output. Programs are run as with the [reference interpreter](https://www.lscheffer.com/malbolge_interp.html) (`<` being the output), the cases it leaves undefined being handled as in the [specification](https://www.lscheffer.com/malbolge_spec.html).
89+
90+
**Codec** | **Conversions** | **Aliases** | **Comment**
91+
:---: | :---: | --- | ---
92+
`malbolge` | text <-> Malbolge program | `mb` | at least two instructions ; whitespace ignored ; invalid characters only accepted with a non-strict errors handling ; programs that do not halt within 1000 steps per instruction (with a minimum of 1 million) are stopped
93+
94+
!!! note "Undefined behaviors"
95+
96+
Executing a character that is not graphic ASCII ends the program, and a modified cell that is no longer graphic ASCII is not enciphered. Without input, `/` gives the end of file (59048).
97+
98+
```python
99+
>>> codext.encode("Hi", "malbolge")
100+
'DCBA@?>=6;:981U543210/.-&%*#G4'
101+
>>> codext.decode("(=<`#9]~6ZY32Vx/4Rs+0No-&Jk)\"Fh}|Bcy?`=*z]Kw%oG4UUS0/@-ejc(:'8dc", "mb")
102+
'Hello World!'
103+
```
104+
105+
-----
106+
86107
### Ook!
87108

88109
[Ook!](https://www.dangermouse.net/esoteric/ook.html) is an esoteric programming language derived from Brainfuck, designed to be read and written by orang-utans: each Brainfuck command is a pair of the words `Ook.`, `Ook?` and `Ook!` (e.g. `Ook. Ook?` for `>` and `Ook! Ook.` for `.`). Short Ook! only keeps the punctuation marks (e.g. `.?` for `>`). Encoding generates a program that prints the text (as UTF-8), while decoding runs the program (with 8-bit cells and no input) and returns its output.

‎src/codext/esoteric/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,6 @@
33
from .brainfuck import *
44
from .cow import *
55
from .lolcode import *
6+
from .malbolge import *
67
from .ook import *
78
from .pikalang import *

‎src/codext/esoteric/malbolge.py‎

Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
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))

‎tests/test_manual.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,21 @@ def test_codec_lolcode(self):
8686
self.assertRaises(ValueError, lolcode_run, "HAI 1.2\nVISIBLE 1\nKTHXBYE 2")
8787
self.assertRaises(ValueError, run, "IM IN YR l\nIM OUTTA YR l", max_steps=100)
8888

89+
def test_codec_malbolge(self):
90+
from codext.esoteric.malbolge import _value, malbolge_run, SIZE
91+
from unittest.mock import patch
92+
# with a non-strict errors handling, invalid characters are skipped
93+
for e in ["ignore", "replace", "leave"]:
94+
self.assertEqual(codecs.decode("D\xe9P", "malbolge", e), "")
95+
# executing a character that is not graphic ASCII ends the program
96+
self.assertEqual(malbolge_run([_value(0, "o"), 200]), b"")
97+
self.assertRaises(ValueError, malbolge_run, [ord(c) for c in "(=BA#9\"=<;:3y7x54-21q/p-,+*)\"!h%B0/.~P<<:(8&66#\"!~}|{zyxwvugJ%"],
98+
max_steps=100)
99+
self.assertRaises(ValueError, codecs.decode, "".join(chr(_value(i, "o")) for i in range(SIZE + 1)),
100+
"malbolge")
101+
with patch("codext.esoteric.malbolge.SIZE", 10):
102+
self.assertRaises(ValueError, codecs.encode, "Hello", "malbolge")
103+
89104
def test_codec_ook(self):
90105
# with a non-strict errors handling, other characters, an odd last word, "Ook? Ook?" and unmatched brackets are
91106
# ignored

0 commit comments

Comments
 (0)