Skip to content

Commit 82491f0

Browse files
committed
Added codec: church
1 parent 0ca59c1 commit 82491f0

5 files changed

Lines changed: 262 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,7 @@ This category also contains `ascii85`, `adobe`, `[x]btoa`, `zeromq` with the `ba
394394

395395
- [X] `befunge`: Befunge-93, two-dimensional esoteric language (encoding generates a program printing the text)
396396
- [X] `brainfuck`: well-known esoteric programming language (encoding generates a program printing the text)
397+
- [X] `church`: Church encoding in the lambda calculus (encoding generates a lambda term of the list of the numerals of the bytes)
397398
- [X] `cow`: esoteric language made of variations of "moo" (Brainfuck-like, with a register and integer output)
398399
- [X] `lolcode`: esoteric language inspired by lolcats (encoding generates a program printing the text), also with lowercase keywords
399400
- [X] `malbolge`: esoteric language designed to be as difficult to program in as possible (encoding generates a program printing the text)

‎docs/pages/enc/esoteric.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,26 @@ Befunge-93 programs are grids of 80x25 cells (wrapping around on the edges) wher
4242

4343
-----
4444

45+
### Church
46+
47+
[Church encoding](https://en.wikipedia.org/wiki/Church_encoding) represents data in the untyped [lambda calculus](https://en.wikipedia.org/wiki/Lambda_calculus), whose terms are variables, abstractions (`\x.M` or `λx.M`, a function of `x`) and applications (`M N`). The natural number *n* is the numeral `\f.\x.f (f ... (f x))`, applying `f` *n* times to `x`, and the list `[a, b, ...]` is its right fold `\c.\n.c a (c b (... n))`. Encoding generates a program that evaluates to the list of the numerals of the bytes of the text (as UTF-8), while decoding evaluates the program and returns the bytes of the list it gives.
48+
49+
The program is a single term: abstractions extend as far to the right as possible, applications are left-associative and `\x y.M` stands for `\x.\y.M`. It is evaluated lazily in normal order (call-by-need), so that only the list and its numerals are reduced, and must give a list of numerals lower than 256.
50+
51+
**Codec** | **Conversions** | **Aliases** | **Comment**
52+
:---: | :---: | --- | ---
53+
`church` | text <-> lambda term of a Church list of Church numerals | `church-encoding`, `lambda-calculus` | variables made of letters, digits, `_` and `'` (not starting with a digit), and bound ; syntax and evaluation errors reported whatever the errors handling ; programs that do not give their list within 1000 steps per token (with a minimum of 1 million) are stopped
54+
55+
```python
56+
>>> codext.encode("\x01\x02", "church")
57+
'\\c.\\n.c (\\f.\\x.f x) (c (\\f.\\x.f (f x)) n)'
58+
>>> mult, n8, n9 = r"(\m n f.m (n f))", r"(\f x.f (f (f (f (f (f (f (f x))))))))", r"(\f x.f (f (f (f (f (f (f (f (f x)))))))))"
59+
>>> codext.decode(rf"\c n.c ({mult} {n8} {n9}) n", "church")
60+
'H'
61+
```
62+
63+
-----
64+
4565
### COW
4666

4767
COW is made of 12 variations of the word "moo". Its memory is a tape of integer cells with a register, and its instructions include those of Brainfuck (`MoO`, `MOo`, `moO`, `mOo`, `MOO`, `moo`, `Moo`), plus integer output and input (`OOM`, `oom`), reset (`OOO`), copy and paste through the register (`MMM`) and the execution of the value of the cell as an instruction (`mOO`). Programs are run as with the reference interpreter, including the quirks of its loops: when searching for their match, `MOO` skips the instruction that follows it and `moo` the one that precedes it.

‎src/codext/esoteric/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# -*- coding: UTF-8 -*-
22
from .befunge import *
33
from .brainfuck import *
4+
from .church import *
45
from .cow import *
56
from .lolcode import *
67
from .malbolge import *

‎src/codext/esoteric/church.py‎

Lines changed: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,228 @@
1+
# -*- coding: UTF-8 -*-
2+
"""Church Codec - Church encoding content encoding.
3+
4+
Church encoding, devised by Alonzo Church, represents data in the untyped lambda calculus, whose terms are variables,
5+
abstractions ("\\x.M" or "λx.M", a function of x) and applications ("M N", M applied to N). The natural number n is the
6+
numeral "\\f.\\x.f (f ... (f x))", applying f n times to x, and the list [a, b, ...] is its right fold
7+
"\\c.\\n.c a (c b (... n))". Encoding generates a program that evaluates to the list of the numerals of the bytes of the
8+
text (as UTF-8), while decoding evaluates the program and returns the bytes of the list it gives.
9+
10+
The program is a single term: abstractions extend as far to the right as possible, applications are left-associative
11+
and "\\x y.M" stands for "\\x.\\y.M". Variables are made of letters, digits, "_" and "'" (not starting with a digit),
12+
and must be bound. The program is evaluated lazily in normal order (call-by-need), so that only the list and its
13+
numerals are reduced, and must give a list of numerals lower than 256. Syntax and evaluation errors are reported
14+
whatever the errors handling. A program that does not give its list within 1000 steps per token (with a minimum of 1
15+
million) is stopped.
16+
17+
This codec:
18+
- en/decodes strings from str to str
19+
- en/decodes strings from bytes to bytes
20+
- decodes file content to str (read)
21+
- encodes file content from str to bytes (write)
22+
23+
Reference: https://en.wikipedia.org/wiki/Church_encoding
24+
https://en.wikipedia.org/wiki/Lambda_calculus
25+
"""
26+
import re
27+
28+
from ._brainfuck import MIN_STEPS, STEPS_PER_COMMAND
29+
from ..__common__ import *
30+
31+
32+
# numerals and arithmetic: SUCC = \n f x.f (n f x), MULT = \m n f.m (n f) ; 8 * 9 = 72 = "H"
33+
_N8, _N9 = r"(\f x.f (f (f (f (f (f (f (f x))))))))", r"(\f x.f (f (f (f (f (f (f (f (f x)))))))))"
34+
__examples__ = {
35+
'enc(church|church-encoding|lambda-calculus)': {
36+
'': r"\c.\n.n",
37+
'\x00': r"\c.\n.c (\f.\x.x) n",
38+
'\x01\x02': r"\c.\n.c (\f.\x.f x) (c (\f.\x.f (f x)) n)",
39+
},
40+
'dec(church)': {
41+
r"\c.\n.n": "",
42+
f"λc n.c ((λm n f.m (n f)) {_N8} {_N9}) n": "H",
43+
f"\\c n.c ((\\n f x.f (n f x)) ((\\m n f.m (n f)) {_N8} {_N9})) n": "I",
44+
# the identity applied to a list, a variable shadowing another one and whitespace
45+
r"(\x.x) (\c.\n.c (\f.\x.f x) n)": "\x01",
46+
"\\c n.c (\\f.(\\f.\\x.f (f x)) f)\n n": "\x02",
47+
# a non-terminating argument is never evaluated (normal order)
48+
r"(\x y.y) ((\x.x x) (\x.x x)) (\c.\n.n)": "",
49+
# syntax errors, unbound variables, results that are not a list of numerals
50+
"": None,
51+
r"\c.\n.": None,
52+
r"\c n n": None,
53+
r"\c.\n.(n": None,
54+
r"\c.\n.n)": None,
55+
r"\c n.c 1 n": None,
56+
r"\c.\n.m": None,
57+
r"\c.\n.c n n": None,
58+
r"\c.\n.c (\f.\x.f) n": None,
59+
r"\c.\n.c (\f.\x.c) n": None,
60+
r"\c.\n.c": None,
61+
r"\c.c": None,
62+
},
63+
'enc-dec(church)': ["", "Hello World!", "@random{64}", "Caf\xe9, \xf1and\xfa & 10€", "\x00a\x00"],
64+
}
65+
__guess__ = ["church"]
66+
67+
68+
_IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_']*")
69+
_TOKEN = re.compile(r"\s+|[λ\\.()]|[A-Za-z_][A-Za-z0-9_']*|.")
70+
# term nodes: (VAR, de Bruijn index), (LAM, body), (APP, function, argument)
71+
VAR, LAM, APP = range(3)
72+
73+
74+
def _err(msg):
75+
raise ChurchDecodeError(f"'church' codec can't decode: {msg}")
76+
77+
78+
def _numeral(n):
79+
""" Church numeral of the given natural number. """
80+
return r"\f.\x." + "f (" * (n - 1) + "f " * (n > 0) + "x" + ")" * (n - 1)
81+
82+
83+
def church_encode(text, errors="strict"):
84+
data = text.encode("utf-8")
85+
return (r := r"\c.\n." + "".join(f"c ({_numeral(b)}) (" for b in data[:-1]) + \
86+
(f"c ({_numeral(data[-1])}) " if data else "") + "n" + ")" * (len(data) - 1)), len(text)
87+
88+
89+
def church_parse(program):
90+
""" Parse a lambda term into nested tuples, variables being replaced by their de Bruijn index. Parsing does not
91+
recurse, as the generated programs nest as deep as their text is long. """
92+
tokens = [t for t in _TOKEN.findall(program) if not t.isspace()]
93+
# each group (the whole program or a parenthesis) holds the pending abstractions, as pairs of the application
94+
# before them and of their number of variables, and its current application
95+
groups, scope, positions, i = [[[], None]], [], {}, 0
96+
97+
def _close():
98+
pending, term = groups.pop()
99+
if term is None:
100+
_err("empty term")
101+
for app, n in reversed(pending):
102+
for _ in range(n):
103+
term = (LAM, term)
104+
positions[scope.pop()].pop()
105+
term = term if app is None else (APP, app, term)
106+
return term
107+
108+
def _add(term):
109+
g = groups[-1]
110+
g[1] = term if g[1] is None else (APP, g[1], term)
111+
112+
while i < len(tokens):
113+
t = tokens[i]
114+
if t in "λ\\":
115+
n = 0
116+
while (i := i + 1) < len(tokens) and _IDENTIFIER.fullmatch(t := tokens[i]):
117+
scope.append(t)
118+
positions.setdefault(t, []).append(len(scope) - 1)
119+
n += 1
120+
if n == 0 or i == len(tokens) or tokens[i] != ".":
121+
_err("bad abstraction (expected variables then '.')")
122+
groups[-1][0].append((groups[-1][1], n))
123+
groups[-1][1] = None
124+
elif t == "(":
125+
groups.append([[], None])
126+
elif t == ")":
127+
if len(groups) == 1:
128+
_err("unmatched ')'")
129+
_add(_close())
130+
elif _IDENTIFIER.fullmatch(t):
131+
if not positions.get(t):
132+
_err(f"unbound variable '{t}'")
133+
_add((VAR, len(scope) - 1 - positions[t][-1]))
134+
else:
135+
_err(f"invalid character '{t}'")
136+
i += 1
137+
if len(groups) > 1:
138+
_err("unmatched '('")
139+
return _close()
140+
141+
142+
def church_run(program, max_steps=None):
143+
""" Evaluate a lambda term giving a Church list of Church numerals and return the bytes of this list.
144+
145+
:param program: lambda term, as a string
146+
:param max_steps: maximum number of steps of the evaluation, for stopping programs that do not give their list (by
147+
default, 1000 per token, with a minimum of 1 million)
148+
"""
149+
term = church_parse(program)
150+
max_steps = max_steps or max(MIN_STEPS, STEPS_PER_COMMAND * len(_TOKEN.findall(program)))
151+
steps = 0
152+
153+
# The terms are evaluated by a lazy Krivine machine: an environment is a linked list of thunks [term, environment,
154+
# value], a value is either a closure (CLO, abstraction, environment) or a free variable applied to thunks (FREE,
155+
# variable, thunks), and the stack holds the thunks of the arguments and the thunks being evaluated (as tuples).
156+
CLO, FREE = range(2)
157+
158+
def _whnf(term, env, stack):
159+
""" Evaluate a term applied to the thunks of the stack (the first argument on top) to weak head normal form. """
160+
nonlocal steps
161+
while True:
162+
if (steps := steps + 1) > max_steps:
163+
raise ValueError(f"program did not give its list within {max_steps} steps")
164+
if term[0] == APP:
165+
stack.append([term[2], env, None])
166+
term = term[1]
167+
elif term[0] == LAM:
168+
if not stack:
169+
return (CLO, term, env)
170+
if isinstance(x := stack.pop(), tuple):
171+
x[0][2] = (CLO, term, env)
172+
else:
173+
term, env = term[1], (x, env)
174+
else:
175+
for _ in range(term[1]):
176+
env = env[1]
177+
th = env[0]
178+
if th[2] is None:
179+
stack.append((th, ))
180+
term, env = th[0], th[1]
181+
elif th[2][0] == CLO:
182+
term, env = th[2][1], th[2][2]
183+
else:
184+
var, args = th[2][1], list(th[2][2])
185+
while stack:
186+
if isinstance(x := stack.pop(), tuple):
187+
x[0][2] = (FREE, var, tuple(args))
188+
else:
189+
args.append(x)
190+
return (FREE, var, tuple(args))
191+
192+
def _apply(value, *variables):
193+
""" Apply a value to free variables. """
194+
args = [[None, None, (FREE, v, ())] for v in variables]
195+
if value[0] == FREE:
196+
return (FREE, value[1], value[2] + tuple(args))
197+
return _whnf(value[1], value[2], args[::-1])
198+
199+
def _force(th):
200+
if th[2] is None:
201+
th[2] = _whnf(th[0], th[1], [])
202+
return th[2]
203+
204+
# the list is read by applying it to the free variables c and n, giving either "c head tail" or "n", and each head
205+
# by applying it to the free variables f and x, giving "f (f (... x))"
206+
c, n, f, x, out = "c", "n", "f", "x", bytearray()
207+
v = _apply(_whnf(term, None, []), c, n)
208+
while v != (FREE, n, ()):
209+
if v[0] != FREE or v[1] != c or len(v[2]) != 2:
210+
_err("the program does not give a list")
211+
b, w = 0, _apply(_force(v[2][0]), f, x)
212+
while w != (FREE, x, ()):
213+
if w[0] != FREE or w[1] != f or len(w[2]) != 1:
214+
_err("an item of the list is not a numeral")
215+
if (b := b + 1) > 255:
216+
_err("an item of the list is greater than 255")
217+
w = _force(w[2][0])
218+
out.append(b)
219+
v = _force(v[2][1])
220+
return bytes(out)
221+
222+
223+
def church_decode(text, errors="strict"):
224+
return (r := ensure_str(church_run(ensure_str(text)))), len(r)
225+
226+
227+
add("church", church_encode, church_decode, r"^(?:church(?:[-_]encoding)?|lambda[-_]calculus)$", printables_rate=1.,
228+
expansion_factor=(400., .004))

‎tests/test_manual.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,18 @@ def test_codec_binhex(self):
2424
self.assertEqual(codecs.decode("This is a test", "binhex", "ignore"), "")
2525
self.assertEqual(codecs.decode(":N!8:", "binhex", "ignore"), "")
2626

27+
def test_codec_church(self):
28+
from codext.esoteric.church import church_run
29+
# a program that does not give its list (e.g. an infinite list) is stopped, while deep terms do not recurse
30+
self.assertRaises(ValueError, church_run, r"(\x.x x) (\x.x x)", max_steps=100)
31+
self.assertRaises(ValueError, church_run, r"(\y.\c.\n.y y c n) (\y.\c.\n.c (\f.\x.x) (y y c n))")
32+
self.assertEqual(church_run(r"(\x.x) (" * 3000 + r"\c.\n.n" + ")" * 3000), b"")
33+
self.assertEqual(codecs.decode(codecs.encode("A" * 1000, "church"), "church"), "A" * 1000)
34+
# syntax errors are reported whatever the errors handling, and numerals must be lower than 256
35+
self.assertRaises(ValueError, codecs.decode, r"\c.\n.n x", "church", "ignore")
36+
self.assertRaises(ValueError, church_run, r"\c.\n.c (\f.\x." + "f (" * 255 + "f x" + ")" * 255 + ") n")
37+
self.assertEqual(church_run(r"\c.\n.c (\f.\x." + "f (" * 254 + "f x" + ")" * 254 + ") n"), b"\xff")
38+
2739
def test_codec_cow(self):
2840
# with a non-strict errors handling, other characters are comments and the program stops at a failing
2941
# instruction

0 commit comments

Comments
 (0)