|
| 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)) |
0 commit comments