Datasets:
File size: 57,337 Bytes
2789d27 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 | #!/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]
|