forked from jsiek/deduce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proof_checker.py
2451 lines (2212 loc) · 96.3 KB
/
proof_checker.py
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
#
# The checking process for programs & proofs has three steps:
#
# 1. process_declarations:
# Collects the type environment for the top-level statements, usually
# from their declared types. (Except for define's without types.)
#
# 2. type_check_stmt:
# Type check the bodies of functions using the type environment.
# Perform overload resolution using the types.
#
# 3. collect_env:
# Collects the proofs (mapping proof labels to their formulas)
# and the values (mapping names to their values, for defines a functions)
# into an environment.
#
# 4. check_proofs:
# Check that the proofs follow the rules of logic
# and run the print and assert statements.
from abstract_syntax import *
from error import error, warning, error_header, get_verbose, set_verbose
imported_modules = set()
checked_modules = set()
name_id = 0
def generate_name(name):
global name_id
ls = name.split('.')
new_id = name_id
name_id += 1
return ls[0] + '.' + str(new_id)
def check_implies(loc, frm1, frm2):
if get_verbose():
print('check_implies? ' + str(frm1) + ' => ' + str(frm2))
match (frm1, frm2):
case (_, Bool(loc2, tyof2, True)):
return
case (_, And(loc2, tyof2, args)):
try:
for arg2 in args:
check_implies(loc, frm1, arg2)
except Exception as e:
msg = str(e) + '\n\nWhile trying to prove that\n\t' + str(frm1) \
+ '\nimplies\n'\
+ '\t' + str(frm2)
raise Exception(msg)
case(Or(loc1, tyof1, args1), _):
for arg1 in args1:
try:
check_implies(loc, arg1, frm2)
except Exception as e:
msg = str(e) + '\n\nWhile trying to prove that\n\t' + str(frm1) \
+ '\nimplies\n'\
+ '\t' + str(frm2)
raise Exception(msg)
case (Bool(loc2, tyof2, False), _):
return
case (And(loc2, tyof2, args1), _):
for arg1 in args1:
try:
check_implies(loc, arg1, frm2)
return
except Exception as e:
# implicit modus ponens
match arg1:
case IfThen(loc3, tyof3, prem, conc):
try:
check_implies(loc, conc, frm2)
rest = And(loc2, tyof2, [arg for arg in args1 if arg != arg1])
check_implies(loc, rest, prem)
return
except Exception as e2:
pass
case _:
pass
continue
error(loc, '\nCould not prove that\n\t' + str(frm1) + '\n' \
+ 'implies\n\t' + str(frm2) + '\n' \
+ 'because we could not prove at least one of\n'
+ '\n'.join(['\t' + str(arg1) + ' implies ' + str(frm2)\
for arg1 in args1]))
case (_, Or(loc2, tyof2, args2)):
for arg2 in args2:
try:
check_implies(loc, frm1, arg2)
return
except Exception as e:
continue
error(loc, '\nCould not prove that\n\t' + str(frm1) + '\n' \
+ 'implies\n\t' + str(frm2) + '\n' \
+ 'because we could not prove at least one of\n'
+ '\n'.join(['\t' + str(frm1) + ' implies ' + str(arg2)\
for arg2 in args2]))
case (IfThen(loc1, tyof1, prem1, conc1), IfThen(loc2, tyof2, prem2, conc2)):
try:
check_implies(loc, prem2, prem1)
check_implies(loc, conc1, conc2)
except Exception as e:
msg = str(e) + '\n\nWhile trying to prove that\n\t' + str(frm1) \
+ '\nimplies\n'\
+ '\t' + str(frm2)
raise Exception(msg)
case (All(loc1, tyof1, var1, _, body1), All(loc2, tyof2, var2, _, body2)):
try:
sub = { var2[0]: Var(loc2, var1[1], var1[0], []) }
body2a = body2.substitute(sub)
check_implies(loc, body1, body2a)
except Exception as e:
msg = str(e) + '\n\nWhile trying to prove that\n\t' + str(frm1) \
+ '\nimplies\n'\
+ '\t' + str(frm2)
raise Exception(msg)
case (All(loc1, tyof1, vars1, _, body1), _):
matching = {}
try:
#print('*** trying to instantiate\n\t' + str(frm1) + '\nto\n\t' + str(frm2))
vars, body = collect_all(frm1)
formula_match(loc, vars, body, frm2, matching, Env())
except Exception as e:
error(loc, '\nCould not prove that\n\t' + str(frm1) \
+ '\ninstantiates to\n\t' + str(frm2) \
+ '\nbecause ' + str(e))
case _:
if frm1 != frm2:
(small_frm1, small_frm2) = isolate_difference(frm1, frm2)
if small_frm1 != frm1:
msg = 'error, the proved formula:\n' \
+ '\t' + str(frm1) + '\n' \
+ 'does not match the goal:\n' \
+ '\t' + str(frm2) + '\n' \
+ 'because\n\t' + str(small_frm1) + '\n\t≠ ' + str(small_frm2) + '\n'
error(loc, msg)
else:
error(loc, '\nCould not prove that\n\t' + str(frm1) \
+ '\nimplies\n\t' + str(frm2))
def instantiate(loc, allfrm, arg):
match allfrm:
case All(loc2, tyof, (var, ty), (s, e), frm):
sub = { var : arg }
ret = frm.substitute(sub)
if s != 0:
ret = update_all_head(ret)
return ret
case _:
error(loc, 'expected all formula to instantiate, not ' + str(allfrm))
def str_of_env(env):
return '{' + ', '.join([k + ": " + str(e) for (k,e) in env.items()]) + '}'
def pattern_to_term(pat):
match pat:
case PatternCons(loc, constr, params):
if len(params) > 0:
ret = Call(loc, None, constr,
[Var(loc, None, param, [param]) for param in params],
False)
return ret
else:
return constr
case _:
error(pat.location, "expected a pattern, not " + str(pat))
num_rewrites = 0
def reset_num_rewrites():
global num_rewrites
num_rewrites = 0
def inc_rewrites():
global num_rewrites
num_rewrites = 1 + num_rewrites
def get_num_rewrites():
global num_rewrites
return num_rewrites
def rewrite(loc, formula, equation):
num_marks = count_marks(formula)
if num_marks == 0:
return rewrite_aux(loc, formula, equation)
elif num_marks == 1:
try:
find_mark(formula)
error(loc, 'in rewrite, find_mark failed on formula:\n\t' + str(formula))
except MarkException as ex:
new_subject = rewrite_aux(loc, ex.subject, equation)
return replace_mark(formula, new_subject)
else:
error(loc, 'in rewrite, formula contains more than one mark:\n\t' + str(formula))
def rewrite_aux(loc, formula, equation):
(lhs, rhs) = split_equation(loc, equation)
if get_verbose():
print('rewrite? ' + str(formula) + ' with equation ' + str(equation) \
+ '\n\t' + str(formula) + ' =? ' + str(lhs) + '\t' + str(formula == lhs))
if formula == lhs:
inc_rewrites()
return rhs
match formula:
case TermInst(loc2, tyof, subject, tyargs, inferred):
return TermInst(loc2, tyof, rewrite_aux(loc, subject, equation), tyargs, inferred)
case Var(loc2, tyof, name, resolved_names):
return formula
case Bool(loc2, tyof, val):
return formula
case And(loc2, tyof, args):
return And(loc2, tyof, [rewrite_aux(loc, arg, equation) for arg in args])
case Or(loc2, tyof, args):
return Or(loc2, tyof, [rewrite_aux(loc, arg, equation) for arg in args])
case IfThen(loc2, tyof, prem, conc):
return IfThen(loc2, tyof, rewrite_aux(loc, prem, equation),
rewrite_aux(loc, conc, equation))
case All(loc2, tyof, var, pos, frm2):
return All(loc2, tyof, var, pos, rewrite_aux(loc, frm2, equation))
case Some(loc2, tyof, vars, frm2):
return Some(loc2, tyof, vars, rewrite_aux(loc, frm2, equation))
case Call(loc2, tyof, rator, args, infix):
call = Call(loc2, tyof,
rewrite_aux(loc, rator, equation),
[rewrite_aux(loc, arg, equation) for arg in args],
infix)
if hasattr(formula, 'type_args'):
call.type_args = formula.type_args
return call
case Switch(loc2, tyof, subject, cases):
return Switch(loc2, tyof, rewrite_aux(loc, subject, equation),
[rewrite_aux(loc, c, equation) for c in cases])
case SwitchCase(loc2, pat, body):
return SwitchCase(loc2, pat, rewrite_aux(loc, body, equation))
case RecFun(loc, name, typarams, params, returns, cases):
return formula
case Conditional(loc2, tyof, cond, thn, els):
return Conditional(loc2, tyof, rewrite_aux(loc, cond, equation),
rewrite_aux(loc, thn, equation),
rewrite_aux(loc, els, equation))
case Lambda(loc2, tyof, vars, body):
return Lambda(loc2, tyof, vars, rewrite_aux(loc, body, equation))
case Generic(loc2, tyof, typarams, body):
return Generic(loc2, tyof, typarams, rewrite_aux(loc, body, equation))
case TAnnote(loc2, tyof, subject, typ):
return TAnnote(loc, tyof, rewrite_aux(loc, subject, equation), typ)
case TLet(loc2, tyof, var, rhs, body):
return TLet(loc2, tyof, var, rewrite_aux(loc, rhs, equation),
rewrite_aux(loc, body, equation))
case Hole(loc2, tyof):
return formula
case Omitted(loc2, tyof):
return formula
case _:
error(loc, 'in rewrite function, unhandled ' + str(formula))
def facts_to_str(env):
result = ''
for (x,p) in env.items():
if isinstance(p, Formula) or isinstance(p, Term):
result += x + ': ' + str(p) + '\n'
return result
def isolate_difference_list(list1, list2):
for (t1, t2) in zip(list1, list2):
diff = isolate_difference(t1, t2)
if diff:
return diff
return None
def isolate_difference(term1, term2):
if get_verbose():
print('isolate_difference(' + str(term1) + ',' + str(term2) + ')')
if term1 == term2:
return None
else:
match (term1, term2):
case (Lambda(l1, tyof1, vs1, body1), Lambda(l2, tyof2, vs2, body2)):
ren = {x: Var(l1, t2, y, []) for ((x,t1),(y,t2)) in zip(vs1, vs2)}
return isolate_difference(body1.substitute(ren), body2)
case (Call(l1, tyof1, fun1, args1, infix1), Call(l2, tyof2, fun2, args2, infix2)):
if fun1 == fun2:
return isolate_difference_list(args1, args2)
else:
return isolate_difference(fun1, fun2)
case (SwitchCase(l1, p1, body1), SwitchCase(l2, p2, body2)):
if p1 == p2:
return isolate_difference(body1, body2)
else:
return (p1, p2)
case (Switch(l1, tyof1, s1, cs1), Switch(l2, tyof2, s2, cs2)):
if s1 == s2:
return isolate_difference_list(cs1, cs2)
else:
return (s1, s2)
case(And(l1, tyof1, args1), And(l2, tyof2, args2)):
return isolate_difference_list(args1, args2)
case (All(l1, tyof1, var1, _, body1), All(l2, tyof2, var2, _, body2)):
return (term1, term2)
case _:
return (term1, term2)
def collect_all_if_then(loc, frm):
"""Returns a list of all variables that need be instantiated, and anythings that need applied"""
match frm:
case All(loc2, tyof, var, _, frm):
(rest_vars, mps) = collect_all_if_then(loc, frm)
x, t = var
return ([Var(loc2, None, x, [])] + rest_vars, mps)
case IfThen(loc2, tyof, prem, conc):
return ([], [(prem, conc)])
case And(loc2, tyof, args):
mps1 = []
for arg in args:
try:
(rest_vars, mps) = collect_all_if_then(loc, arg)
except:
continue
# Making the executive decision that we can't apply for alls nested within ands
if len(rest_vars) > 0: continue
mps1 += mps
if len(mps1) == 0:
error(loc, "in 'apply', expected at least one if-then formula as a conjunct of " + str(frm))
return ([], mps1)
case _:
error(loc, "in 'apply', expected an if-then formula, not " + str(frm))
def collect_all(frm):
match frm:
case All(loc2, tyof, var, _, frm):
(rest_vars, body) = collect_all(frm)
x, t = var
return ([Var(loc2, None, x, [])] + rest_vars, body)
case _:
return ([], frm)
def check_proof(proof, env):
if get_verbose():
print('check_proof:')
print('\t' + str(proof))
ret = None
match proof:
case PRecall(loc, facts):
results = []
for fact in facts:
new_fact = type_check_term(fact, BoolType(loc), env, None, [])
if new_fact in env.proofs():
results.append(new_fact)
else:
error(loc, 'Could not find a proof of\n\t' + str(new_fact) \
+ '\nin the current scope\n' \
+ 'Givens:\n' + env.proofs_str())
if len(results) > 1:
ret = And(loc, BoolType(loc), results)
elif len(results) == 1:
ret = results[0]
else:
error(loc, 'expected some facts after `recall`')
case ApplyDefsFact(loc, definitions, subject):
defs = [type_synth_term(d, env, None, []) for d in definitions]
defs = [d.reduce(env) for d in defs]
formula = check_proof(subject, env)
new_formula = apply_definitions(loc, formula, defs, env)
ret = new_formula
case EnableDefs(loc, definitions, subject):
defs = [type_synth_term(d, env, None, []) for d in definitions]
defs = [d.reduce(env) for d in defs]
old_defs = get_reduce_only()
set_reduce_only(defs + old_defs)
ret = check_proof(subject, env)
set_reduce_only(old_defs)
case RewriteFact(loc, subject, equation_proofs):
formula = check_proof(subject, env)
eqns = [check_proof(proof, env) for proof in equation_proofs]
new_formula = formula.reduce(env)
for eq in eqns:
if not is_equation(eq):
error(loc, 'in rewrite, expected an equation, not:\n\t' + str(eq))
reset_num_rewrites()
new_formula = rewrite(loc, new_formula, eq)
if get_num_rewrites() == 0:
error(loc, 'no matches found for rewrite with\n\t' + str(eq) \
+ '\nin\n\t' + str(new_formula))
new_formula = new_formula.reduce(env)
ret = new_formula
case PHole(loc):
error(loc, 'unfinished proof')
case PSorry(loc):
error(loc, "can't use sorry in context with unkown goal")
case PHelpUse(loc, proof):
formula = check_proof(proof, env)
error(loc, proof_use_advice(proof, formula, env))
case PVar(loc, name):
try:
ret = env.get_formula_of_proof_var(proof)
if ret:
return ret
else:
error(loc, 'could not find given: ' + name)
except Exception as e:
error(loc, str(e))
case PTrue(loc):
ret = Bool(loc, BoolType(loc), True)
case PTLetNew(loc, var, rhs, rest):
new_rhs = type_synth_term(rhs, env, None, [])
body_env = env.define_term_var(loc, var, new_rhs.typeof, new_rhs)
ret = check_proof(rest, body_env)
case PLet(loc, label, frm, reason, rest):
new_frm = check_formula(frm, env)
match new_frm:
case Hole(loc2, tyof):
proved_formula = check_proof(reason, env)
error(loc, "\nhave " + label + ':\n\t' + str(proved_formula))
case _:
check_proof_of(reason, new_frm, env)
body_env = env.declare_local_proof_var(loc, label, remove_mark(new_frm))
ret = check_proof(rest, body_env)
case PAnnot(loc, claim, reason):
new_claim = check_formula(claim, env)
match new_claim:
case Hole(loc2, tyof):
proved_formula = check_proof(reason, env)
error(loc, '\nconclude ' + str(proved_formula))
case _:
check_proof_of(reason, new_claim, env)
ret = remove_mark(new_claim)
case PTerm(loc, term, because, rest):
new_term = type_synth_term(term, env, None, [])
frm = check_proof_of(because, new_term, env)
ret = check_proof(rest, env)
case PTuple(loc, pfs):
frms = [check_proof(pf, env) for pf in pfs]
ret = And(loc, BoolType(loc), frms)
case PAndElim(loc, which, subject):
formula = check_proof(subject, env)
match formula:
case And(loc2, tyof, args):
if which >= len(args):
error(loc, 'out of bounds, access to conjunct ' + str(which) \
+ ' but there are only ' + str(len(args)) + ' conjuncts' \
+ ' in formula\n\t' + str(formula))
ret = args[which]
case _:
error(loc, 'expected a conjunction, not ' + str(formula))
case ImpIntro(loc, label, prem, body):
new_prem = check_formula(prem, env)
body_env = env.declare_local_proof_var(loc, label, new_prem)
conc = check_proof(body, body_env)
ret = IfThen(loc, BoolType(loc), new_prem, conc)
case AllIntro(loc, var, pos, body):
body_env = env
x, ty = var
check_type(ty, env)
if isinstance(ty, TypeType):
body_env = body_env.declare_type(loc, x)
else:
body_env = body_env.declare_term_var(loc, x, ty)
formula = check_proof(body, body_env)
ret = All(loc, BoolType(loc), var, pos, formula)
case AllElim(loc, univ, arg, pos):
allfrm = check_proof(univ, env)
match allfrm:
case All(loc2, tyof, var, _, frm):
sub = {}
v, ty = var
try:
new_arg = type_check_term(arg, ty.substitute(sub), env, None, [])
except Exception as e:
if isinstance(ty, TypeType):
error(loc, f"In instantiation of\n\t{str(univ)} : {str(allfrm)}\n" \
+ f"expected a type argument, but was given '{arg}'")
else:
raise e
if isinstance(ty, TypeType):
error(loc, 'to instantiate:\n\t' + str(univ)+' : '+str(allfrm) \
+'\nwith type arguments, instead write:\n\t' \
+str(univ) + '<' + str(arg) + '>\n')
case _:
error(loc, 'expected all formula to instantiate, not ' + str(allfrm) \
+ '\nGivens:\n' + env.proofs_str())
return instantiate(loc, allfrm, new_arg)
case AllElimTypes(loc, univ, type_arg, _):
allfrm = check_proof(univ, env)
match allfrm:
case All(loc2, tyof, vars, _, frm):
sub = {}
var, ty = vars
check_type(type_arg, env)
if not isinstance(ty, TypeType):
error(loc, 'unexpected term parameter ' + str(var) + ' in type instantiation')
sub[var] = type_arg
case _:
error(loc, 'expected all formula to instantiate, not ' + str(allfrm))
return instantiate(loc, allfrm, type_arg)
case ModusPonens(loc, imp, arg):
ifthen = check_proof(imp, env)
match ifthen:
case IfThen(loc2, tyof, prem, conc):
pass
case All(loc2, tyof, var, _, body):
pass
case And(loc2, tyof, args):
pass
case _:
ifthen = ifthen.reduce(env)
match ifthen:
case IfThen(loc2, tyof, prem, conc):
check_proof_of(arg, prem, env)
ret = conc
case And(loc2, tyof, args):
vars, imps = collect_all_if_then(loc, ifthen)
arg_frm = check_proof(arg, env)
rets = []
for prem, conc in imps:
try:
check_proof_of(arg, prem, env)
rets.append(conc)
except Exception as e:
pass
if len(rets) == 1: ret = rets[0]
elif len(rets) > 1: ret = And(loc2, tyof, rets)
else:
error(loc, "could not prove that " +str(arg_frm) +
" implies at least one of\n\t"\
+ "\n\t".join([str(p) for p, _ in imps])
+ "\nfor application of \n\t"+str(ifthen)
+ "\nto \n\t" + str(arg))
case All(loc2, tyof, _, _, body):
(vars, imps) = collect_all_if_then(loc, ifthen)
rets = []
arg_frm = check_proof(arg, env)
for prem, conc in imps:
try:
matching = {}
formula_match(loc, vars, prem, arg_frm, matching, env)
for x in vars:
if x.name not in matching.keys():
error(loc, "could not deduce an instantiation for variable "\
+ str(x) + '\n' \
+ 'for application of\n\t' + str(ifthen) + '\n'\
+ 'to\n\t' + str(arg))
rets.append(conc.substitute(matching))
except Exception as e:
msg = str(e) + '\nwhile trying to deduce instantiation of\n\t' + str(ifthen) + '\n'\
+ 'to apply to\n\t' + str(arg_frm)
# raise Exception(msg)
if len(rets) == 1: ret = rets[0]
elif len(rets) > 1: ret = And(loc2, tyof, rets)
else:
error(loc, "could not deduce an instantiation for any of the variables "\
+ "for application of \n\t" + str(ifthen) + '\n'\
+ 'to\n\t' + str(arg))
case _:
error(loc, "in 'apply', expected an if-then formula, not " + str(ifthen))
case PInjective(loc, constr, eq_pf):
check_type(constr, env)
formula = check_proof(eq_pf, env)
(a,b) = split_equation(loc, formula)
match (a,b):
case (Call(loc2, tyof2, Var(loc3,t1,f1,rs1), [arg1], infix1),
Call(loc4, tyof4, Var(loc5,t2,f2,rs2), [arg2], infix2)):
if f1 != f2:
error(loc, 'in injective, ' + str(f1) + ' ≠ ' + str(f2))
if constr != f1:
error(loc, 'in injective, ' + str(constr) + ' ≠ ' + str(f1))
if not is_constructor(f1, env):
error(loc, 'in injective, ' + str(f1) + ' not a constructor')
return mkEqual(loc, arg1, arg2)
case _:
error(loc, 'in injective, non-applicable formula: ' + str(formula))
case PSymmetric(loc, eq_pf):
frm = check_proof(eq_pf, env)
(a,b) = split_equation(loc, frm)
return mkEqual(loc, b, a)
case PTransitive(loc, eq_pf1, eq_pf2):
eq1 = check_proof(eq_pf1, env)
eq2 = check_proof(eq_pf2, env)
(a,b1) = split_equation(loc, eq1)
(b2,c) = split_equation(loc, eq2)
b1r = b1.reduce(env)
b2r = b2.reduce(env)
if b1r != b2r:
error(loc, 'error in transitive,\nyou proved\n\t'
+ str(eq1) + '\nand\n\t' + str(eq2) + '\n' \
+ 'but the middle formulas do not match:\n\t' \
+ str(b1r) + '\n≠\n\t' + str(b2r))
else:
return mkEqual(loc, a, c)
case _:
error(proof.location, 'need to be in goal-directed mode for\n\t' + str(proof))
if get_verbose():
print('\t=> ' + str(ret))
return ret
def get_type_name(ty):
match ty:
case Var(l1, tyof, n, rs):
return ty
case TypeInst(l1, ty, type_args):
return get_type_name(ty)
case _:
raise Exception('unhandled case in get_type_name: ' + repr(ty))
def get_type_args(ty):
match ty:
case Var(l1, tyof, n, rs):
return []
case TypeInst(l1, ty, type_args):
return type_args
case _:
raise Exception('unhandled case in get_type_args')
label_count = 0
def reset_label():
label_count = 1
def generate_label():
global label_count
l = 'label_' + str(label_count)
label_count = label_count + 1
return l
def proof_use_advice(proof, formula, env):
prefix = 'Advice about using fact:\n' \
+ '\t' + str(formula) + '\n\n'
match formula:
case Bool(loc, tyof, True):
return prefix + '\tThis fact is useless.\n'
case Bool(loc, tyof, False):
return prefix \
+ '\tThis fact can implicitly prove anything!\n'
case And(loc, tyof, args):
return prefix \
+ '\tThis fact can implicitly prove any of ' \
+ 'the following formulas.\n' \
+ '\n'.join('\t\t' + str(arg) for arg in args)
case Or(loc, tyof, args):
reset_label()
return prefix \
+ '\tProceed with a cases statement:\n' \
+ '\t\tcases ' + str(proof) + '\n' \
+ '\n'.join(['\t\tcase ' + generate_label() + ' : ' + str(arg) + ' { ? }' \
for arg in args])
case IfThen(loc, tyof, prem, conc):
return prefix \
+ '\tApply this if-then formula to a proof of its premise:\n' \
+ '\t\t' + str(prem) + '\n' \
+ '\tto obtain a proof of its conclusion:\n' \
+ '\t\t' + str(conc) + '\n' \
+ '\tby using an apply-to statement:\n' \
+ '\t\tapply ' + str(proof) + ' to ?'
case All(loc, tyof, var, (s, e), body):
vars = [var]
while s != 0:
match body:
case All(loc2, tyof2, var2, (s, e2), body):
vars.append(var2)
letters = []
new_vars = {}
i = 65
type_param = False
for (x,ty) in vars:
if isinstance(ty, TypeType):
type_param = True
letters.append(chr(i))
new_vars[x] = Var(loc,ty, chr(i), [])
i = i + 1
plural = 's' if len(vars) > 1 else ''
pronoun = 'them' if len(vars) > 1 else 'it'
if type_param:
how = ' between `<` and `>` like so:\n' \
+ '\t\t ' + str(proof) + '<' + ', '.join(letters) + '>' + '\n'
else:
how = ' in square-brackets like so:\n' \
+ '\t\t ' + str(proof) + '[' + ', '.join(letters) + ']' + '\n'
return prefix \
+ '\tInstantiate this all formula with your choice' + plural \
+ ' for ' + ', '.join([base_name(x) for (x,ty) in vars]) + '\n' \
+ '\tby writing ' + pronoun + how \
+ '\tto obtain a proof of:\n' \
+ '\t\t' + str(body.substitute(new_vars))
case Some(loc, tyof, vars, body):
letters = []
new_vars = {}
i = 65
for (x,ty) in vars:
letters.append(chr(i))
new_vars[x] = Var(loc,ty, chr(i), [])
i = i + 1
new_body = body.substitute(new_vars)
return prefix \
+ '\tProceed with:\n' \
+ '\t\tobtain ' + ', '.join(letters) + ' where label: ' + str(new_body) + ' from ' + str(proof) +'\n' \
+ '\twhere ' + ', '.join(letters) + (' are new names of your choice' if len(vars) > 1 \
else ' is a new name of your choice' )
case Call(loc2, tyof2, Var(loc3, tyof3, '=', rs), [lhs, rhs], _):
return prefix \
+ '\tYou can use this equality in a rewrite statement:\n' \
+ '\t\trewrite ' + str(proof) + '\n'
case _:
return 'Sorry, I have no advice for this kind of formula.'
def make_unique(name, env):
if name in env:
return make_unique(name + "'", env)
else:
return name
def is_recursive(name, typ):
match typ:
case Var(l1, tyof, n, rs):
return name == n
case TypeInst(l1, ty, type_args):
return is_recursive(name, ty)
case _:
return False
def update_all_head(r):
match r:
case All(loc2, tyof, var, (s, e), frm):
if s == 0:
return All(loc2, tyof, var, (s, e-1), frm)
else:
return All(loc2, tyof, var, (s, e-1), update_all_head(frm))
case _: # THIS SHOULD NEVER HAPPEN
error(loc2, "update_all_head internal error")
def proof_advice(formula, env):
prefix = 'Advice:\n'
match formula:
case Bool(loc, tyof, True):
return prefix + '\tYou can complete the proof with a period.\n'
case Bool(loc, tyof, False):
return prefix \
+ '\tYou can complete the proof by finding a contradiction:\n' \
+ '\tif `np` proves `not P` and `p` proves `P`, \n' \
+ '\tthen `apply np to p` proves false.\n'
case And(loc, tyof, args):
return prefix \
+ '\tYou can complete the proof by separately proving each of ' \
+ 'the following\n\tformulas then combine the proofs with commas.\n' \
+ '\n'.join('\t\t' + str(arg) for arg in args)
case Or(loc, tyof, args):
return prefix \
+ '\tYou can complete the proof by proving any one of the following formulas:\n' \
+ '\n'.join('\t\t' + str(arg) for arg in args)
case IfThen(loc, tyof, prem, conc):
return prefix \
+ '\tYou can complete the proof with:\n' \
+ '\t\tassume label: ' + str(prem) + '\n' \
+ '\tfollowed by a proof of:\n' \
+ '\t\t' + str(conc)
case All(loc, tyof, var, (s, e), body):
x, ty = var
if s != 0:
body = update_all_head(body)
arb_advice = prefix \
+ '\tYou can complete the proof with:\n' \
+ '\t\tarbitrary ' + base_name(x) + ':' + str(ty) + '\n' \
+ '\tfollowed by a proof of:\n' \
+ '\t\t' + str(body)
# NOTE: Maybe we shouldn't give induction advice for non recursively
# defined unions. However right now we will because I haven't added
# that check yet. Maybe even suggest a switch instead.
var_x, var_ty = var
match var_ty:
# NOTE: These are the types that are handled in get_type_name, and
# get_def_of_type_var
case TypeInst() | Var():
pass
case _:
return arb_advice # don't give induction adivce for type variables
# When foralls are generated, the def of type var is not in the environment?
# Seems to be a problem with extensionality
# I'm ok for now with just failing the match if this happens
ty = None
try:
ty = env.get_def_of_type_var(get_type_name(var_ty))
except:
pass
match ty:
case Union(loc2, name, typarams, alts):
if len(alts) < 2:
return arb_advice # Can't do induction if there's only one case
ind_advice = '\n\n\tAlternatively, you can try induction with:\n' \
+ '\t\tinduction ' + str(var_ty) + '\n'
for alt in alts:
match alt:
case Constructor(loc3, constr_name, param_types):
params = [make_unique(type_first_letter(ty)+str(i+1), env)\
for i,ty in enumerate(param_types)]
ind_advice += '\t\tcase ' + base_name(constr_name)
if len(param_types) > 0:
ind_advice += '(' + ', '.join(params) + ')'
num_recursive = sum([1 if is_recursive(name, ty) else 0 \
for ty in param_types])
if num_recursive > 0:
rec_params =[(p,ty) for (p,ty) in zip(params,param_types)\
if is_recursive(name, ty)]
ind_advice += ' suppose '
ind_advice += ',\n\t\t\t'.join(['IH' + str(i+1) + ': ' \
+ str(body.substitute({var_x: Var(loc3, param_ty, param, [])})) \
for i, (param,param_ty) in enumerate(rec_params)])
ind_advice += ' {\n\t\t ?\n\t\t}\n'
return arb_advice + ind_advice
case _:
return arb_advice
case Some(loc, tyof, vars, body):
letters = []
new_vars = {}
i = 65
for (x,ty) in vars:
letters.append(chr(i))
new_vars[x] = Var(loc,ty, chr(i), [])
i = i + 1
return prefix \
+ '\tYou can complete the proof with:\n' \
+ '\t\tchoose ' + ', '.join(letters) + '\n' \
+ '\twhere you replace ' + ', '.join(letters) \
+ ' with your choice(s),\n' \
+ '\tthen prove:\n' \
+ '\t\t' + str(body.substitute(new_vars))
case Call(loc2, tyof2, Var(loc3, tyof3, '=', rs), [lhs, rhs], _):
return prefix \
+ '\tTo prove this equality, one of these statements might help:\n' \
+ '\t\tdefinition\n' \
+ '\t\trewrite\n' \
+ '\t\tequations\n'
case TLet(loc2, _, var, rhs, body):
return proof_advice(body, env)
case _:
for (name, b) in env.dict.items():
if isinstance(b, ProofBinding) and b.local and b.formula == formula:
msg = '\nYou can conclude the proof with:\n'
if base_name(name) == '_':
msg += '\trecall ' + str(formula)
else:
msg += '\tconclude ' + str(formula) \
+ ' by ' + base_name(name)
return msg
return '\nConsider using one of the following givens.\n'
def check_proof_of(proof, formula, env):
if get_verbose():
print('check_proof_of: ' + str(formula) + '?')
print('\t' + str(proof))
match proof:
case PHole(loc):
error(loc, 'incomplete proof\nGoal:\n\t' + str(formula) + '\n'\
+ proof_advice(formula, env) + '\n' \
+ 'Givens:\n' + env.proofs_str())
case PSorry(loc):
warning(loc, 'unfinished proof')
case EnableDefs(loc, definitions, subject):
defs = [type_synth_term(d, env, None, []) for d in definitions]
defs = [d.reduce(env) for d in defs]
old_defs = get_reduce_only()
set_reduce_only(defs + old_defs)
check_proof_of(subject, formula, env)
set_reduce_only(old_defs)
case PReflexive(loc):
match formula:
case Call(loc2, tyof2, Var(loc3, tyof3, '=', rs), [lhs, rhs], _):
lhsNF = lhs.reduce(env)
rhsNF = rhs.reduce(env)
if lhsNF != rhsNF:
(small_lhs, small_rhs) = isolate_difference(lhsNF, rhsNF)
msg = 'error in proof by reflexive:\n'
if small_lhs == lhsNF:
msg = msg + str(lhsNF) + ' ≠ ' + str(rhsNF)
else:
msg = msg + str(small_lhs) + ' ≠ ' + str(small_rhs) + '\n' \
+ 'therefore\n' + str(lhsNF) + ' ≠ ' + str(rhsNF)
error(proof.location, msg + '\n\nGivens:\n\t' + env.proofs_str())
case _:
error(proof.location, 'reflexive proves an equality, not ' \
+ str(formula))
case PSymmetric(loc, eq_pf):
(a,b) = split_equation(loc, formula)
flip_formula = mkEqual(loc, b, a)
check_proof_of(eq_pf, flip_formula, env)
case PTransitive(loc, eq_pf1, eq_pf2):
(a1,c) = split_equation(loc, formula)
eq1 = check_proof(eq_pf1, env)
(a2,b) = split_equation(loc, eq1)
check_proof_of(eq_pf2, mkEqual(loc, b, c), env)
a1r = a1.reduce(env)
a2r = a2.reduce(env)
if remove_mark(a1r) != remove_mark(a2r):
error(loc, 'for transitive,\n\t' + str(a1r) + '\n≠\n\t' + str(a2r))
case PInjective(loc, constr, eq_pf):
check_type(constr, env)
if not is_constructor(constr.name, env):
error(loc, 'in injective, ' + constr.name + ' not a constructor')
(a,b) = split_equation(loc, formula)
lhs = Call(loc, None, constr, [a], False)
rhs = Call(loc, None, constr, [b], False)
flip_formula = mkEqual(loc, lhs, rhs)
check_proof_of(eq_pf, flip_formula, env)
case PExtensionality(loc, proof):
(lhs,rhs) = split_equation(loc, formula)
match lhs.typeof:
case FunctionType(loc2, [], typs, ret_ty):
names = [generate_name('x') for ty in typs]
args = [Var(loc, None, x, []) for x in names]
call_lhs = Call(loc, None, lhs, args, False)
call_rhs = Call(loc, None, rhs, args, False)
formula = mkEqual(loc, call_lhs, call_rhs)
for i, v in enumerate(reversed(list(zip(names, typs)))):
formula = All(loc, None, v, (i, len(names)), formula)
check_proof_of(proof, formula, env)
case FunctionType(loc2, ty_params, params, ret_ty):
error(loc, 'extensionality expects function without any type parameters, not ' + str(len(ty_params)))
case _:
error(loc, 'extensionality expects a function, not ' + str(lhs.typ))
case AllIntro(loc, var, _, body):
x, ty = var
check_type(ty, env)
match formula:
case All(loc2, tyof, var2, (s, e), formula2):
sub = {}
sub[ var2[0] ] = Var(loc, var[1], var[0], [ var[0] ])
frm2 = formula2.substitute(sub)
if s != 0:
frm2 = update_all_head(frm2)
body_env = env.declare_term_vars(loc, [var])
check_proof_of(body, frm2, body_env)
case _:
error(loc, 'arbitrary is proof of an all formula, not\n' \
+ str(formula))
case SomeIntro(loc, witnesses, body):
witnesses = [type_synth_term(trm, env, None, []) for trm in witnesses]