Datasets:
Download tools/lean2zig_lean2zig.py from ego0op/ingot-lean-zig: direct link, hf CLI and curl.
- Browser
- Download file 57.3 kB
-
https://huggingface.co/datasets/ego0op/ingot-lean-zig/resolve/main/tools/lean2zig_lean2zig.py
- Command line
-
hf download hf://datasets/ego0op/ingot-lean-zig/tools/lean2zig_lean2zig.py
-
curl -L -o lean2zig_lean2zig.py https://huggingface.co/datasets/ego0op/ingot-lean-zig/resolve/main/tools/lean2zig_lean2zig.py
57.3 kB
| #!/usr/bin/env python3 | |
| """lean2zig: deterministic, rule-based Lean 4 -> Zig 0.17 converter for the integer-arithmetic subset of theorem statements. | |
| translate(id, statement) -> Unit (Zig text + metadata) or Rejected (named reasons). | |
| Pipeline: lex -> Pratt parse (AST tuples) -> elaborate (Lean's binop% typing: N/Z with type classes, coercions are no-ops on | |
| i128 values) -> typed IR -> bound extraction for the vector generator -> Zig text. No LLM, no randomness at translate time. | |
| Semantics live in lean.zig (ℕ truncated subtraction, Euclidean Int div/mod, x/0 = 0, x%0 = x, overflow-skipping helpers). | |
| """ | |
| import re, zlib, unicodedata | |
| K_VECTORS = 8 # distinct admitted vectors a theorem must reach | |
| BIG_LIT = 1 << 100 # numerals above this are rejected (stay far from i128 overflow) | |
| class Reject(Exception): | |
| def __init__(self, reason): | |
| super().__init__(reason) | |
| self.reason = reason | |
| # ---------------------------------------------------------------- lexer | |
| TOK = re.compile(r""" | |
| (?P<ws>\s+|--[^\n]*) | |
| |(?P<num>\d+(?:\.\d+)?) | |
| |(?P<id>[^\W\d][\w']*(?:\.[^\W\d][\w']*)*) | |
| |(?P<op>:=|<->|->|=>|<=|>=|\\/|/\\|⁻¹|[-+*/%^=<>()\[\]{},:;|!.$@#&~?`"\\…·]|\S) | |
| """, re.X) | |
| def lex(s): | |
| out = [] | |
| for m in TOK.finditer(s): | |
| k = m.lastgroup | |
| if k == 'ws': | |
| continue | |
| t = m.group() | |
| if k == 'id' and t in ('fun', 'λ', 'if', 'then', 'else', 'in', 'with', 'at'): | |
| k = 'kw' | |
| out.append((k, t)) | |
| out.append(('eof', '')) | |
| return out | |
| # ---------------------------------------------------------------- types (type classes for Lean's binop% unification) | |
| class TV: | |
| __slots__ = ('p', 'lo', 'leaves', 'up') | |
| def __init__(self): | |
| self.p = None | |
| self.lo = set() | |
| self.leaves = [] | |
| self.up = set() | |
| def find(t): | |
| while t.p is not None: | |
| t = t.p | |
| return t | |
| def union(a, b): | |
| a, b = find(a), find(b) | |
| if a is b: | |
| return | |
| b.p = a | |
| a.lo |= b.lo | |
| a.leaves += b.leaves | |
| a.up |= b.up | |
| def constrain(tv, t, merge=False): | |
| """The class tv contains a leaf of type t (concrete 'N'/'Z', another TV, or None).""" | |
| if t is None: | |
| return | |
| r = find(tv) | |
| if isinstance(t, str): | |
| r.lo.add(t) | |
| elif merge: | |
| union(r, t) | |
| else: | |
| r.leaves.append(t) | |
| def res(t, seen=None): | |
| if isinstance(t, str): | |
| return t | |
| seen = seen if seen is not None else set() | |
| r = find(t) | |
| if id(r) in seen: | |
| return 'N' | |
| seen.add(id(r)) | |
| if 'Z' in r.lo: | |
| return 'Z' | |
| for l in r.leaves: | |
| if res(l, seen) == 'Z': | |
| return 'Z' | |
| return 'N' | |
| # ---------------------------------------------------------------- parser | |
| BIN = { # op -> (precedence, right_assoc) | |
| '↔': (20, False), '<->': (20, False), '→': (25, True), '->': (25, True), '∨': (30, True), '\\/': (30, True), | |
| '∧': (35, True), '/\\': (35, True), | |
| '=': (50, False), '≠': (50, False), '≤': (50, False), '<=': (50, False), '<': (50, False), '≥': (50, False), '>=': (50, False), | |
| '>': (50, False), '∣': (50, False), '∈': (50, False), '∉': (50, False), '≡': (50, False), | |
| '+': (65, False), '-': (65, False), '*': (70, False), '/': (70, False), '%': (70, False), '^': (75, True), '∘': (90, True), | |
| } | |
| TYPE_HEADS = {'Fin', 'ZMod', 'Set', 'Finset', 'List', 'Multiset', 'Polynomial', 'Matrix', 'Type', 'Sort', 'Prop', 'Array', 'Option', | |
| 'Equiv', 'Function', 'EuclideanSpace', 'Fintype', 'Group', 'Ring', 'Field', 'CommRing', 'Nat.Primes', 'Subgroup'} | |
| REAL_TYPES = {'ℝ': 'real', 'ℚ': 'rat', 'ℂ': 'complex', 'NNReal': 'real', 'ℝ≥0': 'real', 'EReal': 'real', 'ENNReal': 'real'} | |
| class Parser: | |
| def __init__(self, toks): | |
| self.t = toks | |
| self.i = 0 | |
| self.reasons = [] | |
| def why(self, r): | |
| if r not in self.reasons: | |
| self.reasons.append(r) | |
| def peek(self, k=0): | |
| return self.t[min(self.i + k, len(self.t) - 1)] | |
| def nxt(self): | |
| x = self.t[self.i] | |
| self.i = min(self.i + 1, len(self.t) - 1) | |
| return x | |
| def at(self, text): | |
| return self.peek()[1] == text and self.peek()[0] != 'eof' | |
| def eat(self, text): | |
| if self.at(text): | |
| self.nxt() | |
| return True | |
| return False | |
| def need(self, text): | |
| if not self.eat(text): | |
| raise Reject('syntax:expected ' + text) | |
| # --- header | |
| def statement(self): | |
| k, t = self.nxt() | |
| if t not in ('theorem', 'lemma', 'example'): | |
| raise Reject('syntax:not a theorem') | |
| if t != 'example': | |
| self.nxt() # name | |
| binders = [] | |
| while True: | |
| if self.peek()[1] in ('(', '{', '⦃', '['): | |
| save, nreasons = self.i, len(self.reasons) | |
| try: | |
| binders.append(self.binder()) | |
| continue | |
| except Reject: | |
| self.i = save | |
| del self.reasons[nreasons:] | |
| break | |
| if self.peek()[0] == 'id': # bare auto-bound binders: `theorem t a b : P` | |
| j = 0 | |
| while self.peek(j)[0] == 'id': | |
| j += 1 | |
| if self.peek(j)[1] == ':': | |
| binders.append(('vars', [self.nxt()[1] for _ in range(j)], None)) | |
| continue | |
| break | |
| self.eat(':') | |
| concl = self.expr(0) | |
| if not (self.peek()[0] == 'eof' or self.at(':=')): | |
| raise Reject('syntax:trailing ' + self.peek()[1]) | |
| return binders, concl | |
| def binder(self): | |
| op = self.nxt()[1] | |
| if op == '[': | |
| depth = 1 | |
| while depth and self.peek()[0] != 'eof': | |
| x = self.nxt()[1] | |
| depth += (x == '[') - (x == ']') | |
| self.why('typeclass_binder') | |
| return ('skip',) | |
| close = {'(': ')', '{': '}', '⦃': '⦄'}[op] | |
| names = [] | |
| while self.peek()[0] == 'id': | |
| names.append(self.nxt()[1]) | |
| if not self.eat(':'): | |
| self.need(close) | |
| return ('vars', names, None) | |
| ty = self.expr(0) | |
| if self.at(':='): # default value binder | |
| raise Reject('syntax:default binder') | |
| self.need(close) | |
| return ('decl', names, ty) | |
| # --- expressions | |
| def expr(self, rbp): | |
| left = self.prefix() | |
| while True: | |
| k, t = self.peek() | |
| if k not in ('op', 'id') or t not in BIN: | |
| break | |
| prec, right = BIN[t] | |
| if prec < rbp: | |
| break | |
| self.nxt() | |
| rhs = self.expr(prec if right else prec + 1) | |
| if t == '≡': | |
| self.need('[') | |
| kind = self.nxt()[1] | |
| if kind not in ('ZMOD', 'MOD'): | |
| raise Reject('syntax:congruence') | |
| n = self.expr(0) | |
| self.need(']') | |
| left = ('modeq', kind, left, rhs, n) | |
| else: | |
| left = ('bin', t, left, rhs) | |
| return left | |
| def binders_q(self): | |
| """binder list of a quantifier; returns [(name, type_ast|None, pred|None)] up to the comma.""" | |
| out = [] | |
| while not self.at(','): | |
| if self.at('('): | |
| self.nxt() | |
| names = [] | |
| while self.peek()[0] == 'id': | |
| names.append(self.nxt()[1]) | |
| ty = None | |
| if self.eat(':'): | |
| ty = self.expr(0) | |
| self.need(')') | |
| out += [(n, ty, None) for n in names] | |
| elif self.at('{'): | |
| raise Reject('syntax:implicit quantifier binder') | |
| else: | |
| names = [] | |
| while self.peek()[0] == 'id': | |
| names.append(self.nxt()[1]) | |
| if not names: | |
| raise Reject('syntax:quantifier binder') | |
| ty, pred = None, None | |
| if self.eat(':'): | |
| ty = self.expr(0) | |
| elif self.peek()[1] in ('∈', '>', '≥', '<', '≤', '≠', '>=', '<=', '∉'): | |
| op = self.nxt()[1] | |
| pred = (op, self.expr(51)) | |
| out += [(n, ty, pred) for n in names] | |
| if pred is not None: | |
| break | |
| self.need(',') | |
| return out | |
| def prefix(self): | |
| k, t = self.peek() | |
| if k == 'num': | |
| self.nxt() | |
| if '.' in t: | |
| self.why('decimal_literal') | |
| return ('unsup',) | |
| return self.postfix(('num', int(t))) | |
| if k == 'kw': | |
| if t in ('fun', 'λ'): | |
| self.nxt() | |
| names = [] | |
| while not (self.at('=>') or self.at('↦')): | |
| if self.at('('): | |
| self.nxt() | |
| while self.peek()[0] == 'id': | |
| names.append(self.nxt()[1]) | |
| if self.eat(':'): | |
| self.expr(0) | |
| self.need(')') | |
| elif self.peek()[0] == 'id': | |
| names.append(self.nxt()[1]) | |
| else: | |
| raise Reject('syntax:fun binder') | |
| self.nxt() | |
| return ('fun', names, self.expr(0)) | |
| if t == 'if': | |
| self.nxt() | |
| c = self.expr(0) | |
| if self.peek()[1] != 'then': | |
| raise Reject('syntax:if') | |
| self.nxt() | |
| a = self.expr(0) | |
| if self.peek()[1] != 'else': | |
| raise Reject('syntax:if') | |
| self.nxt() | |
| return ('ite', c, a, self.expr(0)) | |
| raise Reject('syntax:keyword ' + t) | |
| if k == 'op': | |
| if t == '(': | |
| self.nxt() | |
| e = self.expr(0) | |
| if self.eat(':'): | |
| ty = self.expr(0) | |
| self.need(')') | |
| return self.postfix(('asc', e, ty)) | |
| if self.at(','): | |
| raise Reject('tuple') | |
| self.need(')') | |
| return self.postfix(('paren', e)) | |
| if t == '-': | |
| self.nxt() | |
| return ('un', '-', self.expr(75)) | |
| if t == '¬': | |
| self.nxt() | |
| return ('un', '¬', self.expr(40)) | |
| if t == '↑': | |
| self.nxt() | |
| return ('coe', self.atom()) | |
| if t == '|': | |
| self.nxt() | |
| e = self.expr(0) | |
| self.need('|') | |
| return self.postfix(('abs', e)) | |
| if t in ('∀', '∃'): | |
| self.nxt() | |
| if t == '∃' and self.at('!'): | |
| raise Reject('unique_exists') | |
| bs = self.binders_q() | |
| return ('q', t, bs, self.expr(0)) | |
| if t in ('∑', '∏'): | |
| self.nxt() | |
| v = self.nxt() | |
| if v[0] != 'id': | |
| raise Reject('syntax:big operator binder') | |
| if self.at(':'): | |
| self.why('big_op_over_type') | |
| raise Reject('big_op_over_type') | |
| if not (self.peek()[1] in ('in', '∈')): | |
| raise Reject('syntax:big operator') | |
| self.nxt() | |
| s = self.expr(51) | |
| if self.peek()[1] == 'with' or self.at('with'): | |
| raise Reject('big_op_filter') | |
| self.need(',') | |
| return ('big', t, v[1], s, self.expr(67)) | |
| if t in ('⌊', '⌈', '√', '⟨', '∫', '∞', '·', '‖', '∅', '{'): | |
| raise Reject('syntax_unsupported:' + t) | |
| raise Reject('syntax:unexpected ' + t) | |
| if k == 'id': | |
| return self.app() | |
| raise Reject('syntax:eof') | |
| def starts_atom(self): | |
| k, t = self.peek() | |
| return k == 'num' or (k == 'id') or t in ('(', '↑', '⟨') | |
| def atom(self): | |
| k, t = self.peek() | |
| if k == 'num': | |
| return self.prefix() | |
| if k == 'id': | |
| self.nxt() | |
| return self.postfix(('id', t)) | |
| if t == '(': | |
| return self.prefix() | |
| if t == '↑': | |
| self.nxt() | |
| return ('coe', self.atom()) | |
| raise Reject('syntax:atom ' + t) | |
| def postfix(self, e): | |
| while True: | |
| if self.at('!'): | |
| self.nxt() | |
| e = ('fact', e) | |
| elif self.at('.') and self.peek(1)[0] == 'id': | |
| self.nxt() | |
| name = self.nxt()[1] | |
| args = [] | |
| while self.starts_atom(): | |
| args.append(self.atom()) | |
| e = ('method', e, name, args) | |
| else: | |
| return e | |
| def app(self): | |
| k, t = self.nxt() | |
| if t in ('Type', 'Sort'): | |
| if self.at('*'): | |
| self.nxt() | |
| elif self.peek()[0] == 'id': | |
| self.nxt() | |
| return ('id', t) | |
| head = self.postfix(('id', t)) | |
| args = [] | |
| while self.starts_atom(): | |
| args.append(self.atom()) | |
| if args: | |
| head = ('app', head, args) | |
| head = self.postfix(head) | |
| return head | |
| # ---------------------------------------------------------------- naming | |
| ZIG_KW = set('addrspace align allowzero and anyframe anytype asm async await break callconv catch comptime const continue defer else enum errdefer error export extern fn for if inline linksection noalias noinline nosuspend opaque or orelse packed pub resume return struct suspend switch test threadlocal try union unreachable var volatile while usingnamespace'.split()) | |
| ZIG_PRIM = set('bool void type anyerror noreturn comptime_int comptime_float usize isize c_int c_uint c_long c_char null undefined true false std lean self'.split()) | |
| GREEK = {'α': 'alpha', 'β': 'beta', 'γ': 'gamma', 'δ': 'delta', 'ε': 'epsilon', 'ζ': 'zeta', 'η': 'eta', 'θ': 'theta', 'ι': 'iota', 'κ': 'kappa', | |
| 'μ': 'mu', 'ν': 'nu', 'ξ': 'xi', 'ο': 'omicron', 'π': 'pi', 'ρ': 'rho', 'σ': 'sigma', 'τ': 'tau', 'υ': 'upsilon', 'φ': 'phi', 'χ': 'chi', | |
| 'ψ': 'psi', 'ω': 'omega', 'Γ': 'Gamma', 'Δ': 'Delta', 'Θ': 'Theta', 'Λ': 'Lambda', 'Ξ': 'Xi', 'Φ': 'Phi', 'Ψ': 'Psi', 'Ω': 'Omega'} | |
| SUBS = {'₀': '0', '₁': '1', '₂': '2', '₃': '3', '₄': '4', '₅': '5', '₆': '6', '₇': '7', '₈': '8', '₉': '9'} | |
| def zig_name(lean, taken): | |
| s = '' | |
| for ch in lean: | |
| if ch in SUBS: | |
| s += SUBS[ch] | |
| elif ch in GREEK: | |
| s += GREEK[ch] | |
| elif ch == "'": | |
| s += 'Prime' | |
| elif ch.isascii() and (ch.isalnum() or ch == '_'): | |
| s += ch | |
| else: | |
| d = unicodedata.normalize('NFKD', ch).encode('ascii', 'ignore').decode() | |
| s += d if d.isalnum() else 'x' | |
| if not s or s[0].isdigit(): | |
| s = 'v' + s | |
| if s in ZIG_KW or s in ZIG_PRIM or re.fullmatch(r'[iuf]\d+', s) or s == '_': | |
| s += '_' | |
| base, n = s, 1 | |
| while s in taken: | |
| n += 1 | |
| s = base + str(n) | |
| if re.fullmatch(r'[iuf]\d+', s): | |
| s += '_' | |
| taken.add(s) | |
| return s | |
| def camel_id(ident): | |
| parts = [p for p in re.split(r'[^A-Za-z0-9]+', ident) if p] | |
| parts = [p for p in parts if p.lower() not in ('lean',)] or parts | |
| s = parts[0][:1].lower() + parts[0][1:] + ''.join(p[:1].upper() + p[1:] for p in parts[1:]) | |
| if not s or s[0].isdigit(): | |
| s = 'thm' + s | |
| return s | |
| # ---------------------------------------------------------------- elaborator | |
| # name -> (kind, zig fn, [arg classes], result) arg class: 'N' natural, 'Z' integer, 'P' poly (shares class with result) | |
| FUNCS = { | |
| 'Nat.choose': ('call', 'lean.choose', 'NN', 'N'), 'choose': ('call', 'lean.choose', 'NN', 'N'), | |
| 'Nat.factorial': ('call', 'lean.factorial', 'N', 'N'), 'factorial': ('call', 'lean.factorial', 'N', 'N'), | |
| 'Nat.gcd': ('call', 'lean.gcd', 'NN', 'N'), 'Int.gcd': ('call', 'lean.gcd', 'ZZ', 'N'), 'gcd': ('call', 'lean.gcd', 'PP', 'P'), | |
| 'Nat.lcm': ('call', 'lean.lcm', 'NN', 'N'), 'Int.lcm': ('call', 'lean.lcm', 'ZZ', 'N'), 'lcm': ('call', 'lean.lcm', 'PP', 'P'), | |
| 'Int.natAbs': ('call', 'lean.abs', 'Z', 'N'), 'Int.toNat': ('call', 'lean.toNat', 'Z', 'N'), | |
| 'abs': ('call', 'lean.abs', 'P', 'P'), 'Nat.fib': ('call', 'lean.fib', 'N', 'N'), 'fib': ('call', 'lean.fib', 'N', 'N'), | |
| 'Nat.succ': ('succ', None, 'N', 'N'), 'Nat.pred': ('pred', None, 'N', 'N'), 'Nat.sqrt': ('call', 'lean.isqrt', 'N', 'N'), | |
| 'Nat.totient': ('call', 'lean.totient', 'N', 'N'), 'φ': ('call', 'lean.totient', 'N', 'N'), 'totient': ('call', 'lean.totient', 'N', 'N'), | |
| 'max': ('call', '@max', 'PP', 'P'), 'min': ('call', '@min', 'PP', 'P'), 'Nat.max': ('call', '@max', 'NN', 'N'), 'Nat.min': ('call', '@min', 'NN', 'N'), | |
| } | |
| PREDS = { # name -> (zig, arg classes) | |
| 'Nat.Prime': ('lean.isPrime', 'N'), 'Prime': ('lean.isPrime', 'P'), 'Nat.prime': ('lean.isPrime', 'N'), | |
| 'Even': ('even', 'P'), 'Odd': ('odd', 'P'), | |
| 'Nat.Coprime': ('coprime', 'NN'), 'Nat.coprime': ('coprime', 'NN'), 'Coprime': ('coprime', 'NN'), 'IsCoprime': ('coprime', 'ZZ'), | |
| 'Int.Prime': ('lean.isPrime', 'P'), | |
| } | |
| METHODS = { # method name -> (namespace function names by receiver class N/Z) | |
| 'choose': ('Nat.choose', None), 'factorial': ('Nat.factorial', None), 'gcd': ('Nat.gcd', 'Int.gcd'), 'lcm': ('Nat.lcm', 'Int.lcm'), | |
| 'natAbs': (None, 'Int.natAbs'), 'toNat': (None, 'Int.toNat'), 'succ': ('Nat.succ', None), 'pred': ('Nat.pred', None), | |
| 'sqrt': ('Nat.sqrt', None), 'totient': ('Nat.totient', None), 'fib': ('Nat.fib', None), | |
| 'Prime': ('Nat.Prime', 'Int.Prime'), 'prime': ('Nat.Prime', None), 'Coprime': ('Nat.Coprime', 'IsCoprime'), 'Even': ('Even', 'Even'), 'Odd': ('Odd', 'Odd'), | |
| 'max': ('Nat.max', None), 'min': ('Nat.min', None), | |
| } | |
| SET_FUNS = {'Finset.range', 'range', 'Finset.Icc', 'Icc', 'Finset.Ico', 'Ico', 'Finset.Ioc', 'Ioc', 'Finset.Ioo', 'Ioo', | |
| 'Set.Icc', 'Set.Ico', 'Set.Ioc', 'Set.Ioo', 'Finset.Iio', 'Set.Ici', 'Set.Ioi', 'Set.Iic', 'Nat.Icc'} | |
| class Var: | |
| __slots__ = ('z', 'ty', 'lean') | |
| def __init__(self, z, ty, lean): | |
| self.z, self.ty, self.lean = z, ty, lean | |
| def head_name(e): | |
| while e[0] in ('paren',): | |
| e = e[1] | |
| return e[1] if e[0] == 'id' else None | |
| class Elab: | |
| def __init__(self, reasons): | |
| self.reasons = reasons | |
| self.env = {} | |
| self.implicit = {} | |
| self.taken = set() | |
| self.params = [] # Var in declaration order (top level binders, hoisted foralls, autobound) | |
| self.hyps = [] # IR bool | |
| self.checks = [] # (tv, upper) type mismatch checks | |
| self.counter = 0 | |
| def why(self, r): | |
| if r not in self.reasons: | |
| self.reasons.append(r) | |
| def label(self, p): | |
| self.counter += 1 | |
| return '%s%d' % (p, self.counter) | |
| # --- binder types | |
| def classify_type(self, ty): | |
| """-> 'N' | 'Z' | ('bad', reason) | None (not a type: a proposition).""" | |
| while ty[0] == 'paren': | |
| ty = ty[1] | |
| if ty[0] == 'id': | |
| if ty[1] == 'ℕ' or ty[1] == 'Nat': | |
| return 'N' | |
| if ty[1] == 'ℤ' or ty[1] == 'Int': | |
| return 'Z' | |
| if ty[1] in REAL_TYPES: | |
| return ('bad', 'type_' + REAL_TYPES[ty[1]]) | |
| if ty[1] in TYPE_HEADS: | |
| return ('bad', 'type_' + ty[1]) | |
| return None | |
| if ty[0] == 'app' and head_name(ty[1]) in TYPE_HEADS: | |
| return ('bad', 'type_' + head_name(ty[1])) | |
| if ty[0] == 'bin' and ty[1] in ('→', '->'): | |
| a, b = self.classify_type(ty[2]), self.classify_type(ty[3]) | |
| if a is not None and b is not None: | |
| return ('bad', 'function_binder') | |
| return None | |
| def new_var(self, lean, ty, implicit=False): | |
| v = Var(zig_name(lean, self.taken), ty, lean) | |
| self.env[lean] = v | |
| if implicit: | |
| self.implicit[lean] = v | |
| return v | |
| def declare(self, binders): | |
| for b in binders: | |
| if b[0] == 'skip': | |
| continue | |
| _, names, ty = b | |
| if ty is None: | |
| for n in names: | |
| self.params.append(self.new_var(n, TV())) | |
| continue | |
| c = self.classify_type(ty) | |
| if c is None: # hypotheses | |
| self.hyps.append(self.prop(ty)) | |
| elif isinstance(c, tuple): | |
| self.why(c[1]) | |
| for n in names: | |
| self.env[n] = Var('?', None, n) | |
| else: | |
| for n in names: | |
| self.params.append(self.new_var(n, c)) | |
| # --- hoisting prenex forall / implications of the conclusion | |
| def conclusion(self, ast): | |
| while True: | |
| if ast[0] == 'paren': | |
| ast = ast[1] | |
| elif ast[0] == 'q' and ast[1] == '∀': | |
| for (n, ty, pred) in ast[2]: | |
| t = TV() if ty is None else self.classify_type(ty) | |
| if isinstance(t, tuple): | |
| self.why(t[1]) | |
| self.env[n] = Var('?', None, n) | |
| continue | |
| if t is None: | |
| self.why('quantifier_type') | |
| self.env[n] = Var('?', None, n) | |
| continue | |
| if pred is not None and pred[0] == '∈': | |
| t = self.set_type(pred[1]) or t | |
| v = self.new_var(n, t) | |
| self.params.append(v) | |
| if pred is not None: | |
| self.hyps.append(self.binder_pred(v, pred)) | |
| ast = ast[3] | |
| elif ast[0] == 'bin' and ast[1] in ('→', '->'): | |
| self.hyps.append(self.prop(ast[2])) | |
| ast = ast[3] | |
| else: | |
| return self.prop(ast) | |
| def set_type(self, s): | |
| """Type class of the elements of a Finset/Set interval expression, or None.""" | |
| s = s[1] if s[0] == 'paren' else s | |
| if s[0] == 'app' and head_name(s[1]) in SET_FUNS: | |
| tv = TV() | |
| for a in s[2]: | |
| self.tree(a, tv) | |
| return tv | |
| return None | |
| def binder_pred(self, v, pred): | |
| op, e = pred | |
| x = ('var', v.z) | |
| if op == '∈': | |
| return self.membership(x, e, v.ty) | |
| tv = TV() | |
| constrain(tv, v.ty, merge=isinstance(v.ty, TV)) | |
| ie = self.tree(e, tv) | |
| m = {'>': '>', '≥': '≥', '<': '<', '≤': '≤', '>=': '≥', '<=': '≤', '≠': '≠'} | |
| if op == '∉': | |
| return ('not', self.membership(x, e, v.ty)) | |
| return ('cmp', m[op], x, ie) | |
| # --- props | |
| def prop(self, a): | |
| k = a[0] | |
| if k == 'paren': | |
| return self.prop(a[1]) | |
| if k == 'id': | |
| if a[1] == 'True': | |
| return ('const', 'true') | |
| if a[1] == 'False': | |
| return ('const', 'false') | |
| return self.pred_app(a) | |
| if k == 'bin': | |
| op = a[1] | |
| if op in ('∧', '/\\'): | |
| return ('and', self.prop(a[2]), self.prop(a[3])) | |
| if op in ('∨', '\\/'): | |
| return ('or', self.prop(a[2]), self.prop(a[3])) | |
| if op in ('↔', '<->'): | |
| return ('iff', self.prop(a[2]), self.prop(a[3])) | |
| if op in ('→', '->'): | |
| return ('imp', self.prop(a[2]), self.prop(a[3])) | |
| if op in ('=', '≠', '≤', '<=', '<', '≥', '>=', '>'): | |
| tv = TV() | |
| ia, ib = self.tree(a[2], tv), self.tree(a[3], tv) | |
| m = {'<=': '≤', '>=': '≥'} | |
| return ('cmp', m.get(op, op), ia, ib) | |
| if op == '∣': | |
| tv = TV() | |
| ia, ib = self.tree(a[2], tv), self.tree(a[3], tv) | |
| return ('call', 'lean.dvd', [ia, ib]) | |
| if op in ('∈', '∉'): | |
| tv = TV() | |
| x = self.tree(a[2], tv) | |
| r = self.membership(x, a[3], tv) | |
| return r if op == '∈' else ('not', r) | |
| self.why('not_a_prop:' + op) | |
| return ('const', 'false') | |
| if k == 'un' and a[1] == '¬': | |
| return ('not', self.prop(a[2])) | |
| if k == 'modeq': | |
| tv = TV() | |
| constrain(tv, 'Z' if a[1] == 'ZMOD' else 'N') | |
| return ('call', 'lean.modeq', [self.tree(a[2], tv), self.tree(a[3], tv), self.tree(a[4], tv)]) | |
| if k == 'q': | |
| return self.quant(a) | |
| if k in ('app', 'method', 'id'): | |
| return self.pred_app(a) | |
| self.why('prop_form:' + k) | |
| return ('const', 'false') | |
| def membership(self, x, s, ty): | |
| s = s[1] if s[0] == 'paren' else s | |
| if s[0] == 'app' and head_name(s[1]) in SET_FUNS: | |
| h = head_name(s[1]).split('.')[-1] | |
| tv = TV() | |
| constrain(tv, ty, merge=isinstance(ty, TV)) | |
| args = [self.tree(e, tv) for e in s[2]] | |
| if h == 'range' and len(args) == 1: | |
| return ('and', ('cmp', '≤', ('lit', 0), x), ('cmp', '<', x, args[0])) | |
| if len(args) == 2 and h in ('Icc', 'Ico', 'Ioc', 'Ioo'): | |
| lo = ('cmp', '≤' if h in ('Icc', 'Ico') else '<', args[0], x) | |
| hi = ('cmp', '≤' if h in ('Icc', 'Ioc') else '<', x, args[1]) | |
| return ('and', lo, hi) | |
| self.why('membership:' + (head_name(s[1]) if s[0] == 'app' else s[0])) | |
| return ('const', 'false') | |
| def split_call(self, a): | |
| """-> (receiver|None, name, args) for an id / application / method call, else None.""" | |
| if a[0] == 'id': | |
| recv, name, args = None, a[1], [] | |
| elif a[0] == 'app': | |
| h = a[1] | |
| if h[0] == 'id': | |
| recv, name, args = None, h[1], list(a[2]) | |
| elif h[0] == 'method': | |
| recv, name, args = h[1], h[2], list(h[3]) + list(a[2]) | |
| else: | |
| return None | |
| elif a[0] == 'method': | |
| recv, name, args = a[1], a[2], list(a[3]) | |
| else: | |
| return None | |
| if recv is None and '.' in name: | |
| base, _, meth = name.rpartition('.') | |
| if base in self.implicit and base not in self.env: | |
| self.env[base] = self.implicit[base] | |
| if base in self.env and self.env[base].z != '?': | |
| recv, name = ('id', base), meth | |
| return recv, name, args | |
| def pred_app(self, a): | |
| sc = self.split_call(a) | |
| if sc is None: | |
| self.why('pred:' + a[0]) | |
| return ('const', 'false') | |
| recv, name, args = sc | |
| if recv is not None: | |
| nm = METHODS.get(name) | |
| if nm is None: | |
| self.why('method:' + name) | |
| return ('const', 'false') | |
| ty = res(self.tree_type(recv)) | |
| name = nm[1] if ty == 'Z' and nm[1] else nm[0] | |
| args = [recv] + list(args) | |
| if name is None: | |
| self.why('method:' + sc[1]) | |
| return ('const', 'false') | |
| if name in PREDS: | |
| z, cls = PREDS[name] | |
| if len(args) != len(cls): | |
| self.why('pred_arity:' + name) | |
| return ('const', 'false') | |
| tvs = TV() | |
| irs = [self.arg(e, c, tvs) for e, c in zip(args, cls)] | |
| if z == 'even': | |
| return ('cmp', '=', ('mod', irs[0], ('lit', 2)), ('lit', 0)) | |
| if z == 'odd': | |
| return ('cmp', '=', ('mod', irs[0], ('lit', 2)), ('lit', 1)) | |
| if z == 'coprime': | |
| return ('cmp', '=', ('call', 'lean.gcd', irs), ('lit', 1)) | |
| return ('call', z, irs) | |
| self.why('pred:' + name) | |
| return ('const', 'false') | |
| def tree_type(self, e): | |
| tv = TV() | |
| self.tree(e, tv) | |
| return tv | |
| # --- quantifiers | |
| def quant(self, a): | |
| kind, bs, body = a[1], a[2], a[3] | |
| saved = dict(self.env) | |
| vs = [] | |
| for (n, ty, pred) in bs: | |
| t = TV() if ty is None else self.classify_type(ty) | |
| if isinstance(t, tuple): | |
| self.why(t[1]) | |
| t = TV() | |
| elif t is None: | |
| self.why('quantifier_type') | |
| t = TV() | |
| if pred is not None and pred[0] == '∈': | |
| t = self.set_type(pred[1]) or t | |
| v = self.new_var(n, t) | |
| vs.append((v, pred)) | |
| ib = self.prop(body) | |
| for v, pred in reversed(vs): | |
| if pred is not None: | |
| p = self.binder_pred(v, pred) | |
| ib = ('imp', p, ib) if kind == '∀' else ('and', p, ib) | |
| ib = ('q', kind, v.z, v.ty, ib) | |
| self.env = saved | |
| return ib | |
| # --- arithmetic trees | |
| def arg(self, e, cls, shared): | |
| """An argument of a function with parameter class cls ('N','Z','P').""" | |
| if cls == 'P': | |
| return self.tree(e, shared) | |
| tv = TV() | |
| ir = self.tree(e, tv) | |
| if cls == 'N': | |
| tv.up.add('N') | |
| self.checks.append(tv) | |
| return ir | |
| def tree(self, e, tv): | |
| k = e[0] | |
| if k == 'paren': | |
| return self.tree(e[1], tv) | |
| if k == 'num': | |
| if e[1] > BIG_LIT: | |
| self.why('huge_literal') | |
| return ('lit', e[1]) | |
| if k == 'bin' and e[1] in ('+', '-', '*', '/', '%'): | |
| a, b = self.tree(e[2], tv), self.tree(e[3], tv) | |
| op = e[1] | |
| if op == '-': | |
| return ('sub', a, b, tv) | |
| return ({'+': 'add', '*': 'mul', '/': 'div', '%': 'mod'}[op], a, b) | |
| if k == 'bin' and e[1] == '^': | |
| a = self.tree(e[2], tv) | |
| tv2 = TV() | |
| b = self.tree(e[3], tv2) | |
| tv2.up.add('N') | |
| self.checks.append(tv2) | |
| return ('pow', a, b) | |
| if k == 'un' and e[1] == '-': | |
| constrain(tv, 'Z') | |
| return ('neg', self.tree(e[2], tv)) | |
| if k == 'abs': | |
| tv2 = TV() | |
| ir = self.tree(e[1], tv2) | |
| constrain(tv, tv2) | |
| return ('call', 'lean.abs', [ir]) | |
| if k == 'fact': | |
| tv2 = TV() | |
| ir = self.tree(e[1], tv2) | |
| tv2.up.add('N') | |
| self.checks.append(tv2) | |
| constrain(tv, 'N') | |
| return ('call', 'lean.factorial', [ir]) | |
| if k == 'asc': | |
| t = self.classify_type(e[2]) | |
| if isinstance(t, tuple): | |
| self.why(t[1]) | |
| return ('lit', 0) | |
| if t is None: | |
| self.why('ascription_type') | |
| return ('lit', 0) | |
| tv2 = TV() | |
| tv2.up.add(t) | |
| tv2.lo.add(t) | |
| self.checks.append(tv2) | |
| ir = self.tree(e[1], tv2) | |
| constrain(tv, t) | |
| return ir | |
| if k == 'coe': | |
| tv2 = TV() | |
| return self.tree(e[1], tv2) | |
| if k == 'ite': | |
| tv2 = TV() | |
| c = self.prop(e[1]) | |
| a, b = self.tree(e[2], tv2), self.tree(e[3], tv2) | |
| constrain(tv, tv2) | |
| return ('ite', c, a, b) | |
| if k == 'big': | |
| return self.big(e, tv) | |
| if k in ('id', 'app', 'method'): | |
| return self.leaf(e, tv) | |
| if k == 'unsup': | |
| return ('lit', 0) | |
| self.why('term_form:' + k) | |
| return ('lit', 0) | |
| def lookup(self, name): | |
| return self.env.get(name) | |
| def leaf(self, e, tv): | |
| if e[0] == 'id' and e[1] in self.implicit and e[1] not in self.env: | |
| self.env[e[1]] = self.implicit[e[1]] | |
| if e[0] == 'id' and e[1] in self.env: | |
| v = self.env[e[1]] | |
| if v.z == '?': | |
| return ('lit', 0) | |
| constrain(tv, v.ty, merge=isinstance(v.ty, TV)) | |
| return ('var', v.z) | |
| sc = self.split_call(e) | |
| if sc is None: | |
| self.why('app_head:' + e[0]) | |
| return ('lit', 0) | |
| recv, name, args = sc | |
| if recv is None and (name in self.env or name in self.implicit): | |
| self.why('function_application:var') | |
| return ('lit', 0) | |
| if recv is not None and name in ('sum', 'prod', 'card'): | |
| if name == 'card' and not args: | |
| return self.card_call(recv, tv) | |
| if name != 'card' and len(args) == 1: | |
| return self.sum_call('∑' if name == 'sum' else '∏', recv, args[0], tv) | |
| if recv is not None: | |
| nm = METHODS.get(name) | |
| if nm is None: | |
| self.why('method:' + name) | |
| return ('lit', 0) | |
| rty = res(self.tree_type(recv)) | |
| fname = nm[1] if rty == 'Z' and nm[1] else nm[0] | |
| if fname is None or fname not in FUNCS: | |
| self.why('method:' + name) | |
| return ('lit', 0) | |
| return self.call(fname, [recv] + args, tv) | |
| if recv is None and name in ('Finset.sum', 'Finset.prod') and len(args) == 2: | |
| return self.sum_call('∑' if name.endswith('sum') else '∏', args[0], args[1], tv) | |
| if recv is not None and name in ('sum', 'prod') and len(args) == 1: | |
| return self.sum_call('∑' if name == 'sum' else '∏', recv, args[0], tv) | |
| if recv is None and name in ('Finset.card', 'card') and len(args) == 1: | |
| return self.card_call(args[0], tv) | |
| if recv is not None and name == 'card' and not args: | |
| return self.card_call(recv, tv) | |
| if name in FUNCS and FUNCS[name]: | |
| return self.call(name, args, tv) | |
| if not args and re.fullmatch(r"[A-Za-z][A-Za-z0-9_']*|[α-ωΑ-Ω][\w']*", name) and name not in KNOWN_FN and (len(name) <= 2 or not name[0].isupper()): | |
| # autobound implicit variable (Lean infers its type from use) | |
| v = self.new_var(name, TV(), implicit=True) | |
| self.params.append(v) | |
| constrain(tv, v.ty, merge=True) | |
| return ('var', v.z) | |
| self.why('fn:' + name) | |
| return ('lit', 0) | |
| def call(self, fname, args, tv): | |
| kind, z, cls, ret = FUNCS[fname] | |
| if len(args) != len(cls): | |
| self.why('fn_arity:' + fname) | |
| return ('lit', 0) | |
| shared = TV() | |
| irs = [self.arg(a, c, shared) for a, c in zip(args, cls)] | |
| rt = shared if ret == 'P' else ret | |
| constrain(tv, rt) | |
| if kind == 'succ': | |
| return ('add', irs[0], ('lit', 1)) | |
| if kind == 'pred': | |
| return ('sub', irs[0], ('lit', 1), 'N') | |
| return ('call', z, irs) | |
| def big(self, e, tv): | |
| return self.setloop(e[1], e[2], e[3], e[4], tv) | |
| def unparen(self, e): | |
| while e[0] == 'paren': | |
| e = e[1] | |
| return e | |
| def setloop(self, op, vname, s, body, tv): | |
| """Finite sum / product / count over a Finset interval, Nat.divisors, or a Finset.filter of those. | |
| op: '∑', '∏', '#' (for '#' body is None and the result counts the elements passing the filters).""" | |
| s = self.unparen(s) | |
| conds = [] | |
| while s[0] == 'app' and head_name(s[1]) == 'Finset.filter' and len(s[2]) == 2: | |
| conds.append(self.unparen(s[2][0])) | |
| s = self.unparen(s[2][1]) | |
| if not (s[0] == 'app' and head_name(s[1]) in SET_FUNS | {'Nat.divisors'}): | |
| self.why('big_set:' + (head_name(s[1]) if s[0] == 'app' else s[0])) | |
| return ('lit', 0) | |
| h = head_name(s[1]).split('.')[-1] | |
| saved = dict(self.env) | |
| tvs = TV() | |
| args = [] | |
| for a in s[2]: | |
| if h in ('range', 'divisors'): | |
| t2 = TV() | |
| t2.up.add('N') | |
| self.checks.append(t2) | |
| args.append(self.tree(a, t2)) | |
| else: | |
| args.append(self.tree(a, tvs)) | |
| extra = None | |
| if h == 'range' and len(args) == 1: | |
| lo, hi = ('lit', 0), ('sub', args[0], ('lit', 1), 'Z') | |
| vty = 'N' | |
| elif h == 'divisors' and len(args) == 1: | |
| lo, hi, vty = ('lit', 1), args[0], 'N' | |
| extra = args[0] | |
| elif len(args) == 2 and h in ('Icc', 'Ico', 'Ioc', 'Ioo'): | |
| lo = args[0] if h in ('Icc', 'Ico') else ('add', args[0], ('lit', 1)) | |
| hi = args[1] if h in ('Icc', 'Ioc') else ('sub', args[1], ('lit', 1), 'Z') | |
| vty = tvs | |
| else: | |
| self.why('big_set:' + h) | |
| self.env = saved | |
| return ('lit', 0) | |
| v = self.new_var(vname, vty) | |
| cond = None | |
| if extra is not None: | |
| cond = ('call', 'lean.dvd', [('var', v.z), extra]) | |
| for c in conds: | |
| if c[0] != 'fun' or len(c[1]) != 1: | |
| self.why('filter_predicate') | |
| continue | |
| self.env[c[1][0]] = v | |
| pc = self.prop(c[2]) | |
| cond = pc if cond is None else ('and', cond, pc) | |
| tvb = TV() | |
| ib = None if op == '#' else self.tree(body, tvb) | |
| self.env = saved | |
| if op == '#': | |
| constrain(tv, 'N') | |
| else: | |
| constrain(tv, tvb) | |
| return ('big', op, v.z, lo, hi, ib, self.label({'∑': 'sum', '∏': 'prod', '#': 'count'}[op]), cond) | |
| def sum_call(self, op, setast, funast, tv): | |
| f = self.unparen(funast) | |
| if f[0] != 'fun' or len(f[1]) != 1: | |
| self.why('big_function') | |
| return ('lit', 0) | |
| return self.setloop(op, f[1][0], setast, f[2], tv) | |
| def card_call(self, setast, tv): | |
| s = self.unparen(setast) | |
| return self.setloop('#', 'x', s, None, tv) if not self.is_filter_with_var(s) else self.setloop('#', self.filter_var(s), s, None, tv) | |
| def is_filter_with_var(self, s): | |
| return s[0] == 'app' and head_name(s[1]) == 'Finset.filter' and len(s[2]) == 2 and self.unparen(s[2][0])[0] == 'fun' | |
| def filter_var(self, s): | |
| return self.unparen(s[2][0])[1][0] | |
| KNOWN_FN = {'π', 'Real.pi', 'exp', 'sqrt', 'cos', 'sin', 'tan', 'log', 'exp', 'logb', 'cosh', 'sinh', 'arctan', 'arcsin', 'arccos', 'floor', 'ceil', 'deriv', 'id', 'rexp', 'fract', | |
| 'card', 'digits', 'divisors', 'sorry', 'decide', 'rfl', 'sum', 'prod', 'ofNat', 'cast', 'natCast', 'min', 'max', 'abs'} | |
| # ---------------------------------------------------------------- IR utilities | |
| def ir_walk(ir): | |
| if isinstance(ir, tuple): | |
| yield ir | |
| for x in ir[1:]: | |
| if isinstance(x, (tuple, list)): | |
| yield from ir_walk(x) | |
| elif isinstance(ir, list): | |
| for x in ir: | |
| yield from ir_walk(x) | |
| def ir_vars(ir): | |
| return {n[1] for n in ir_walk(ir) if isinstance(n, tuple) and n and n[0] == 'var'} | |
| def has_loop(ir): | |
| return any(n[0] in ('q', 'big') for n in ir_walk(ir) if isinstance(n, tuple)) | |
| def const_eval(ir): | |
| if ir[0] == 'lit': | |
| return ir[1] | |
| if ir[0] in ('add', 'mul') : | |
| a, b = const_eval(ir[1]), const_eval(ir[2]) | |
| if a is None or b is None: | |
| return None | |
| return a + b if ir[0] == 'add' else a * b | |
| if ir[0] == 'sub': | |
| a, b = const_eval(ir[1]), const_eval(ir[2]) | |
| return None if a is None or b is None else a - b | |
| if ir[0] == 'neg': | |
| a = const_eval(ir[1]) | |
| return None if a is None else -a | |
| return None | |
| # ---------------------------------------------------------------- emitter | |
| CMP = {'=': '==', '≠': '!=', '≤': '<=', '<': '<', '≥': '>=', '>': '>'} | |
| FLIP = {'<': '>', '>': '<', '≤': '≥', '≥': '≤', '=': '=', '≠': '≠'} | |
| class Emit: | |
| def __init__(self): | |
| self.depth = 0 | |
| def val(self, ir, ind): | |
| k = ir[0] | |
| if k == 'lit': | |
| return str(ir[1]) | |
| if k == 'var': | |
| return ir[1] | |
| if k in ('add', 'mul', 'div', 'mod', 'pow'): | |
| return 'lean.%s(%s, %s)' % (k, self.val(ir[1], ind), self.val(ir[2], ind)) | |
| if k == 'sub': | |
| ty = ir[3] if isinstance(ir[3], str) else res(ir[3]) | |
| return 'lean.%s(%s, %s)' % ('sub' if ty == 'Z' else 'monus', self.val(ir[1], ind), self.val(ir[2], ind)) | |
| if k == 'neg': | |
| if ir[1][0] == 'lit': | |
| return '-%d' % ir[1][1] | |
| return 'lean.neg(%s)' % self.val(ir[1], ind) | |
| if k == 'call': | |
| return '%s(%s)' % (ir[1], ', '.join(self.val(a, ind) for a in ir[2])) | |
| if k == 'ite': | |
| return '@as(i128, if (%s) %s else %s)' % (self.bool(ir[1], ind), self.val(ir[2], ind), self.val(ir[3], ind)) | |
| if k == 'big': | |
| return self.big(ir, ind) | |
| raise AssertionError(k) | |
| def big(self, ir, ind): | |
| _, op, z, lo, hi, body, lab, cond = ir | |
| p = ' ' * (ind + 4) | |
| init, f = ('1', 'mul') if op == '∏' else ('0', 'add') | |
| term = '1' if op == '#' else self.val(body, ind + 4) | |
| step = 'Acc = lean.%s(%sAcc, %s);' % (f, z, term) | |
| if cond is not None: | |
| step = 'if (%s) %s' % (self.bool(cond, ind + 4), step.replace('Acc =', 'Acc =', 1)) | |
| step = step.replace('if (', 'if (', 1) | |
| step = '%s' % step | |
| line = '%swhile (%s <= %sHi) : (%s += 1) { if (%s) %sAcc = lean.%s(%sAcc, %s); }\n' % ( | |
| p, z, z, z, self.bool(cond, ind + 4), z, f, z, term) | |
| else: | |
| line = '%swhile (%s <= %sHi) : (%s += 1) %sAcc = lean.%s(%sAcc, %s);\n' % (p, z, z, z, z, f, z, term) | |
| return ('%s: {\n%sconst %sLo: i128 = %s;\n%sconst %sHi: i128 = %s;\n%sif (!lean.spanOk(%sLo, %sHi)) break :%s 0;\n' | |
| '%svar %sAcc: i128 = %s;\n%svar %s: i128 = %sLo;\n%s%sbreak :%s %sAcc;\n%s}' | |
| % (lab, p, z, self.val(lo, ind + 4), p, z, self.val(hi, ind + 4), p, z, z, lab, | |
| p, z, init, p, z, z, line, p, lab, z, ' ' * ind)) | |
| def bool(self, ir, ind): | |
| k = ir[0] | |
| if k == 'const': | |
| return ir[1] | |
| if k == 'cmp': | |
| return '(%s %s %s)' % (self.val(ir[2], ind), CMP[ir[1]], self.val(ir[3], ind)) | |
| if k == 'and': | |
| return '(%s and %s)' % (self.bool(ir[1], ind), self.bool(ir[2], ind)) | |
| if k == 'or': | |
| return '(%s or %s)' % (self.bool(ir[1], ind), self.bool(ir[2], ind)) | |
| if k == 'iff': | |
| return '(%s == %s)' % (self.bool(ir[1], ind), self.bool(ir[2], ind)) | |
| if k == 'imp': | |
| return '(!%s or %s)' % (self.bool(ir[1], ind), self.bool(ir[2], ind)) | |
| if k == 'not': | |
| return '!%s' % self.bool(ir[1], ind) | |
| if k == 'call': | |
| return '%s(%s)' % (ir[1], ', '.join(self.val(a, ind) for a in ir[2])) | |
| if k == 'q': | |
| return self.quant(ir, ind) | |
| raise AssertionError(k) | |
| def quant(self, ir, ind): | |
| _, kind, z, ty, body = ir | |
| lo, hi = quant_bounds(ir) | |
| r = res(ty) | |
| p = ' ' * (ind + 4) | |
| lab = 'blk_' + ('all' if kind == '∀' else 'any') + re.sub(r'\W', '', z) | |
| complete = (hi is not None) and (lo is not None or r == 'N') | |
| self.depth += 1 | |
| W = {1: 40, 2: 16, 3: 8}.get(self.depth, 5) | |
| if lo is None: | |
| if r == 'N': | |
| lo_t = '0' | |
| elif hi is not None: | |
| lo_t = 'lean.sub(%s, %d)' % (self.val(hi, ind + 4), W) | |
| else: | |
| lo_t = str(-W) | |
| else: | |
| lo_t = self.val(lo, ind + 4) | |
| if hi is None: | |
| hi_t = str(W) if lo is None and r == 'Z' else 'lean.add(%sLo, %d)' % (z, 2 * W) | |
| else: | |
| hi_t = self.val(hi, ind + 4) | |
| out = '%s: {\n%sconst %sLo: i128 = %s;\n%sconst %sHi: i128 = %s;\n' % (lab, p, z, lo_t, p, z, hi_t) | |
| if complete: | |
| out += '%sif (!lean.spanOk(%sLo, %sHi)) break :%s %s;\n' % (p, z, z, lab, 'true' if kind == '∀' else 'false') | |
| out += '%svar %s: i128 = %sLo;\n%swhile (%s <= %sHi) : (%s += 1) {\n' % (p, z, z, p, z, z, z) | |
| if kind == '∀': | |
| out += '%s if (!%s) break :%s false;\n%s}\n' % (p, self.bool(body, ind + 4), lab, p) | |
| out += '%sbreak :%s %s;\n' % (p, lab, 'true' if complete else 'lean.giveUp()') | |
| else: | |
| out += '%s if (%s) break :%s true;\n%s}\n' % (p, self.bool(body, ind + 4), lab, p) | |
| out += '%sbreak :%s %s;\n' % (p, lab, 'false' if complete else '!lean.giveUp()') | |
| self.depth -= 1 | |
| return out + ' ' * ind + '}' | |
| def conjuncts(ir, through_imp=False): | |
| out = [] | |
| def go(x): | |
| if x[0] == 'and': | |
| go(x[1]); go(x[2]) | |
| elif x[0] == 'imp' and through_imp: | |
| go(x[1]) | |
| # the consequent of a chain of implications also constrains nothing; only antecedents count | |
| y = x[2] | |
| while y[0] == 'imp': | |
| go(y[1]) | |
| y = y[2] | |
| else: | |
| out.append(x) | |
| go(ir) | |
| return out | |
| def bounds_from_atoms(atoms, z, allowed): | |
| """lo/hi IR expressions for variable z from comparison atoms; allowed = names the bound may mention.""" | |
| los, his = [], [] | |
| for a in atoms: | |
| if a[0] != 'cmp': | |
| continue | |
| op, l, r = a[1], a[2], a[3] | |
| for x, e, o in ((l, r, op), (r, l, FLIP[op])): | |
| if x == ('var', z) and ir_vars(e) <= allowed and z not in ir_vars(e) and not has_loop(e): | |
| if o == '≥': | |
| los.append(e) | |
| elif o == '>': | |
| los.append(('add', e, ('lit', 1))) | |
| elif o == '≤': | |
| his.append(e) | |
| elif o == '<': | |
| his.append(('sub', e, ('lit', 1), 'Z')) | |
| elif o == '=': | |
| los.append(e); his.append(e) | |
| return los, his | |
| def pick_bound(es, which): | |
| if not es: | |
| return None | |
| return es[0] # first usable bound; others are enforced by the body/hypotheses | |
| def quant_bounds(ir): | |
| """Bounds of a quantifier variable, computed once and cached on the node's body via closure of allowed names.""" | |
| return QB.get(id(ir), (None, None)) | |
| QB = {} | |
| def annotate_quant_bounds(ir, scope): | |
| """Fill QB for every quantifier in ir. scope = set of variable names visible outside.""" | |
| if not isinstance(ir, tuple): | |
| return | |
| if ir[0] == 'q': | |
| _, kind, z, ty, body = ir | |
| atoms = conjuncts(body, through_imp=True) if kind == '∀' else conjuncts(body) | |
| los, his = bounds_from_atoms(atoms, z, scope) | |
| lo, hi = (pick_bound(los, 'lo'), pick_bound(his, 'hi')) | |
| # two bounds: use the tighter one only when constant; otherwise first (body re-checks the rest) | |
| QB[id(ir)] = (lo, hi) | |
| annotate_quant_bounds(body, scope | {z}) | |
| return | |
| for x in ir[1:]: | |
| if isinstance(x, tuple): | |
| annotate_quant_bounds(x, scope) | |
| elif isinstance(x, list): | |
| for y in x: | |
| annotate_quant_bounds(y, scope) | |
| # ---------------------------------------------------------------- vector plan | |
| def occurrences(ir, z): | |
| return sum(1 for n in ir_walk(ir) if isinstance(n, tuple) and n[0] == 'var' and n[1] == z) | |
| def isolate(z, L, R): | |
| """Solve L = R for z when z occurs once in L along a chain of +, -, neg and multiplication by a nonzero numeral; else None. | |
| Division in the result is exact only if a solution exists; the hypotheses are still evaluated afterwards.""" | |
| if L == ('var', z): | |
| return R | |
| k = L[0] | |
| if k == 'add': | |
| a, b = L[1], L[2] | |
| if occurrences(a, z) == 1 and occurrences(b, z) == 0: | |
| return isolate(z, a, ('sub', R, b, 'Z')) | |
| if occurrences(b, z) == 1 and occurrences(a, z) == 0: | |
| return isolate(z, b, ('sub', R, a, 'Z')) | |
| elif k == 'sub' and res(L[3]) == 'Z' if k == 'sub' else False: | |
| a, b = L[1], L[2] | |
| if occurrences(a, z) == 1 and occurrences(b, z) == 0: | |
| return isolate(z, a, ('add', R, b)) | |
| if occurrences(b, z) == 1 and occurrences(a, z) == 0: | |
| return isolate(z, b, ('sub', a, R, 'Z')) | |
| elif k == 'neg': | |
| return isolate(z, L[1], ('neg', R)) | |
| elif k == 'mul': | |
| a, b = L[1], L[2] | |
| for c, x in ((a, b), (b, a)): | |
| cv = const_eval(c) | |
| if cv is not None and cv != 0 and occurrences(x, z) == 1: | |
| return isolate(z, x, ('div', R, c)) | |
| return None | |
| def make_plan(params, hyps): | |
| """Order the parameters and give each a draw range or a defining expression, from the hypotheses' top-level atoms.""" | |
| atoms = [] | |
| for h in hyps: | |
| atoms += conjuncts(h) | |
| names = [p.z for p in params] | |
| cand = {z: [] for z in names} | |
| for a in atoms: | |
| if a[0] != 'cmp': | |
| continue | |
| op, l, r = a[1], a[2], a[3] | |
| for x, e, o in ((l, r, op), (r, l, FLIP[op])): | |
| if x[0] == 'var' and x[1] in cand and x[1] not in ir_vars(e) and not has_loop(e) and o != '≠': | |
| cand[x[1]].append((o, e, ir_vars(e))) | |
| if op == '=' and not has_loop(l) and not has_loop(r): | |
| for z in names: | |
| for side, other in ((l, r), (r, l)): | |
| if side[0] != 'var' and occurrences(side, z) == 1 and occurrences(other, z) == 0: | |
| iso = isolate(z, side, other) | |
| if iso is not None and z not in ir_vars(iso): | |
| cand[z].append(('=', iso, ir_vars(iso))) | |
| placed, order = set(), [] | |
| remaining = list(names) | |
| em = Emit() | |
| while remaining: | |
| pick = None | |
| for z in remaining: | |
| if all(d <= placed for (_, _, d) in cand[z]): | |
| pick = z | |
| break | |
| if pick is None: | |
| pick = min(remaining, key=lambda z: sum(1 for c in cand[z] if not c[2] <= placed)) | |
| remaining.remove(pick) | |
| usable = [c for c in cand[pick] if c[2] <= placed] | |
| placed.add(pick) | |
| order.append((pick, usable)) | |
| plan = [] | |
| for z, usable in order: | |
| p = next(p for p in params if p.z == z) | |
| ty = res(p.ty) | |
| defs = [c for c in usable if c[0] == '='] | |
| if defs: | |
| plan.append({'z': z, 'def': defs[0][1], 'ty': ty}) | |
| continue | |
| los = [e if o == '≥' else ('add', e, ('lit', 1)) for (o, e, _) in usable if o in ('≥', '>')] | |
| his = [e if o == '≤' else ('sub', e, ('lit', 1), 'Z') for (o, e, _) in usable if o in ('≤', '<')] | |
| plan.append({'z': z, 'lo': los, 'hi': his, 'ty': ty}) | |
| return plan | |
| def plan_cardinality(plan): | |
| """Product of the literal range sizes of drawn variables, or None when some range is open or depends on a variable.""" | |
| card = 1 | |
| for d in plan: | |
| if 'def' in d: | |
| continue | |
| lo = [const_eval(e) for e in d['lo']] | |
| hi = [const_eval(e) for e in d['hi']] | |
| if any(x is None for x in lo + hi) or not hi: | |
| return None | |
| l = max(lo + ([0] if d['ty'] == 'N' else [])) | |
| if not lo and d['ty'] != 'N': | |
| return None | |
| card *= max(0, min(hi) - l + 1) | |
| return card | |
| # ---------------------------------------------------------------- unit assembly | |
| def collapse(s): | |
| s = re.sub(r'\s+', ' ', s).strip() | |
| return ''.join(c for c in s if c >= ' ' and c != '\x7f') | |
| def statement_text(src): | |
| s = collapse(src) | |
| s = re.sub(r'\s*:=\s*by\s+sorry\s*$', '', s) | |
| s = re.sub(r'\s*:=.*$', '', s) | |
| return s | |
| class Unit: | |
| def __init__(self, **kw): | |
| self.__dict__.update(kw) | |
| class Rejected: | |
| def __init__(self, reasons): | |
| self.reasons = reasons | |
| def translate(ident, src): | |
| reasons = [] | |
| p = Parser(lex(src)) | |
| try: | |
| binders, concl = p.statement() | |
| except Reject as r: | |
| return Rejected(p.reasons + [r.reason]) | |
| except RecursionError: | |
| return Rejected(['syntax:too deep']) | |
| reasons = list(p.reasons) | |
| el = Elab(reasons) | |
| try: | |
| el.declare(binders) | |
| ic = el.conclusion(concl) | |
| except Reject as r: | |
| return Rejected(reasons + [r.reason]) | |
| except RecursionError: | |
| return Rejected(['syntax:too deep']) | |
| for tv in el.checks: | |
| r = find(tv) | |
| if 'N' in r.up and res(tv) == 'Z': | |
| el.why('type_mismatch') | |
| if reasons: | |
| return Rejected(reasons) | |
| if any(v.z == '?' for v in el.env.values()): | |
| return Rejected(['internal:unresolved binder']) | |
| # untyped quantifier/auto-bound variables: default class | |
| params = el.params | |
| hyps = el.hyps | |
| all_irs = hyps + [ic] | |
| QB.clear() | |
| annotate_quant_bounds(ic, set(p.z for p in params)) | |
| for h in hyps: | |
| annotate_quant_bounds(h, set(p.z for p in params)) | |
| plan = make_plan(params, hyps) | |
| heavy = any(has_loop(x) for x in all_irs) | |
| return build_unit(ident, src, params, hyps, ic, plan, heavy) | |
| def build_unit(ident, src, params, hyps, ic, plan, heavy): | |
| em = Emit() | |
| fn = camel_id(ident) | |
| used_h = set() | |
| for h in hyps: | |
| used_h |= ir_vars(h) | |
| used_c = ir_vars(ic) | |
| pnames = [p.z for p in params] | |
| hp = [z for z in pnames if z in used_h] | |
| cp = [z for z in pnames if z in used_c] | |
| # a conclusion that is a top-level '=' gets one function per side | |
| sides = ic[0] == 'cmp' and ic[1] == '=' and not (ir_vars(ic[2]) == set() and ir_vars(ic[3]) == set() and False) | |
| out = ['/// ' + statement_text(src)] | |
| def sig(name, ps, ret): | |
| return 'pub fn %s(%s) %s {' % (name, ', '.join('%s: i128' % z for z in ps), ret) | |
| hyp_expr = None | |
| if hyps: | |
| hyp_expr = hyps[0] | |
| for h in hyps[1:]: | |
| hyp_expr = ('and', hyp_expr, h) | |
| out.append(sig(fn + 'Hypotheses', hp, 'bool')) | |
| out.append(' return %s;' % em.bool(hyp_expr, 4)) | |
| out.append('}') | |
| out.append('') | |
| if sides: | |
| l_ps = [z for z in pnames if z in ir_vars(ic[2])] | |
| r_ps = [z for z in pnames if z in ir_vars(ic[3])] | |
| out.append(sig(fn + 'Lhs', l_ps, 'i128')) | |
| out.append(' return %s;' % em.val(ic[2], 4)) | |
| out.append('}') | |
| out.append('') | |
| out.append(sig(fn + 'Rhs', r_ps, 'i128')) | |
| out.append(' return %s;' % em.val(ic[3], 4)) | |
| out.append('}') | |
| out.append('') | |
| concl_call = '%sLhs(%s) == %sRhs(%s)' % (fn, ', '.join(l_ps), fn, ', '.join(r_ps)) | |
| else: | |
| out.append(sig(fn + 'Conclusion', cp, 'bool')) | |
| out.append(' return %s;' % em.bool(ic, 4)) | |
| out.append('}') | |
| out.append('') | |
| concl_call = '%sConclusion(%s)' % (fn, ', '.join(cp)) | |
| # test block | |
| seed = zlib.crc32(src.encode('utf8')) | |
| drawn = [d['z'] for d in plan if d['z'] in (used_h | used_c)] | |
| plan = [d for d in plan if d['z'] in (used_h | used_c)] | |
| free = [d for d in plan if 'def' not in d] | |
| t = ['test "%s" {' % fn] | |
| if free or any('def' in d for d in plan): | |
| card = plan_cardinality(plan) | |
| need = K_VECTORS if card is None else min(K_VECTORS, card) | |
| if not free: | |
| need = 1 | |
| if free: | |
| t.append(' var src = lean.Source.init(%d, %d, %s);' % (seed, len(free), 'true' if heavy else 'false')) | |
| t.append(' var tally = lean.Tally(%d).init();' % len(drawn)) | |
| t.append(' while (src.next()) {' if free else ' for (0..1) |_| {') | |
| if not free: | |
| t.append(' lean.begin();') | |
| for d in plan: | |
| if 'def' in d: | |
| t.append(' const %s: i128 = %s;' % (d['z'], em.val(d['def'], 8))) | |
| if d['ty'] == 'N': | |
| t.append(' if (%s < 0) continue;' % d['z']) | |
| continue | |
| los = [em.val(e, 8) for e in d['lo']] | |
| his = ['lean.top'] + [em.val(e, 8) for e in d['hi']] | |
| if d['ty'] == 'N': | |
| los = ['0'] + los | |
| elif not los: | |
| los = ['-lean.top'] | |
| lo = los[0] if len(los) == 1 else '@max(%s)' % ', '.join(los) | |
| hi = his[0] if len(his) == 1 else '@min(%s)' % ', '.join(his) | |
| t.append(' const %s = src.pick(%s, %s) orelse continue;' % (d['z'], lo, hi)) | |
| if hyps: | |
| t.append(' if (!%sHypotheses(%s) or lean.skipped()) continue;' % (fn, ', '.join(hp))) | |
| t.append(' try tally.admit(%s, .{ %s });' % (concl_call, ', '.join(drawn))) | |
| t.append(' }') | |
| t.append(' try tally.require(%d);' % need) | |
| else: | |
| t.append(' lean.begin();') | |
| if hyps: | |
| t.append(' const hyp = %sHypotheses();' % fn) | |
| t.append(' if (lean.skipped()) return error.OnlySkipped;') | |
| t.append(' if (!hyp) return error.NoVector;') | |
| t.append(' const ok = %s;' % concl_call) | |
| t.append(' if (lean.skipped()) return error.OnlySkipped;') | |
| t.append(' try std.testing.expect(ok);') | |
| t.append('}') | |
| out += t | |
| text = '\n'.join(out) + '\n' | |
| return Unit(id=ident, fn=fn, text=text, nparams=len(params), heavy=heavy, sides=sides, nhyps=len(hyps), | |
| body=body_of(text), seed=seed) | |
| def body_of(text): | |
| """The function bodies without doc comment and without the test block (for structure comparison).""" | |
| return text.split('\ntest "')[0] | |