summaryrefslogtreecommitdiff
path: root/vikalpa.scm
blob: 480bbca174199c673ad7dab1d84716d1832eb8be (about) (plain)
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
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
;;; Vikalpa --- Proof Assistant
;;; Copyright © 2020, 2021 Masaya Tojo <masaya@tojo.tokyo>
;;;
;;; This file is part of Vikalpa.
;;;
;;; Vikalpa is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; Vikalpa is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;;; General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with Vikalpa.  If not, see <http://www.gnu.org/licenses/>.

(define-module (vikalpa)
  #:export (system?
            system-rewrite
            system-check
            system-apropos
            system-eval
            system-lookup
            set-measure-predicate
            set-measure-less-than
            core-system
            core-system/equal-t-nil
            define-system
            define-proof
            define-core-function
            define-core-function/guard
            define-function
            define-function
            define-function/guard
            define-axiom-function
            define-axiom-function/guard
            define-syntax-rules
            define-axiom
            define-theorem
            define-guard-theorem
            admit)
  #:use-module (ice-9 match)
  #:use-module (ice-9 format)
  #:use-module (ice-9 control)
  #:use-module (ice-9 exceptions)
  #:use-module (ice-9 regex)
  #:use-module (ice-9 pretty-print)
  #:use-module ((srfi srfi-1)
                #:select (every any lset-union fold append-map find
                                filter-map))
  #:use-module (srfi srfi-8)
  #:use-module (srfi srfi-11)
  #:use-module (srfi srfi-26)
  #:use-module (oop goops))

(define-class <system> ()
  (definitions
    #:getter get-definitions
    #:init-keyword #:definitions
    #:init-value '())
  (equal-symbol #:getter get-equal-symbol
                #:init-value 'equal?
                #:init-keyword #:equal-symbol)
  (true-object #:getter get-true-object
               #:init-value ''#t
               #:init-keyword #:true-object)
  (false-object #:getter get-false-object
                #:init-value ''#f
                #:init-keyword #:false-object)
  (measure-predicate #:getter get-measure-predicate
                     #:init-value #f)
  (measure-less-than #:getter get-measure-less-than
                     #:init-value #f))

(define-syntax-rule (true) (get-true-object (current-system)))
(define-syntax-rule (false) (get-false-object (current-system)))

(define-class <definition> ()
  (name #:getter get-name
        #:init-keyword #:name)
  (variables #:getter get-variables
             #:init-keyword #:variables
             #:init-value '()))

(define-class <provable> ())

(define-class <proved> (<provable>)
  (claim #:getter get-claim #:init-keyword #:claim)
  (proof #:getter get-proof #:init-keyword #:proof))

(define-class <admitted> ())

(define-class <theorem*> (<definition>)
  (expression #:getter get-expression #:init-keyword #:expression))

(define-class <conjecture> (<theorem*> <provable>))
(define-class <theorem> (<theorem*> <proved>))
(define-class <axiom> (<theorem*>))
(define-class <admitted-theorem> (<theorem*> <proved> <admitted>))

(define-class <function*> (<definition>)
  (guards #:getter get-guards #:init-keyword #:guards))
(define-class <core-function> (<function*>)
  (procedure #:getter get-procedure #:init-keyword #:procedure))
(define-class <expandable-function> (<function*>)
  (expression #:getter get-expression #:init-keyword #:expression)
  (code #:getter get-code #:init-keyword #:code))
(define-class <function> (<expandable-function> <provable>))
(define-class <total-function> (<expandable-function> <proved>))
(define-class <admitted-function> (<expandable-function> <proved> <admitted>))

(define-class <macro> (<definition>)
  (mrules #:getter macro-mrules #:init-keyword #:mrules)
  (literals #:getter macro-literals #:init-keyword #:literals))

(define (write-definition sym d port)
  (format port "#<~a: ~s>"
          sym (cons (get-name d) (get-variables d))))

(define-method (display (s <system>) port)
  (format port "#<system: function: ~a theorem: ~a macro: ~a>"
          (length (filter (cut is-a? <> <function*>)
                          (get-definitions s)))
          (length (filter (cut is-a? <> <theorem*>)
                          (get-definitions s)))
          (length (filter (cut is-a? <> <macro>)
                          (get-definitions s)))))

(define-method (write (s <system>) port)
  (format port "#<system: function: ~a theorem: ~a macro: ~a>"
          (length (filter (cut is-a? <> <function*>)
                          (get-definitions s)))
          (length (filter (cut is-a? <> <theorem*>)
                          (get-definitions s)))
          (length (filter (cut is-a? <> <macro>)
                          (get-definitions s)))))

(define-method (lookup name (s <system>))
  (find (lambda (x)
          (equal? name (get-name x)))
        (get-definitions s)))

(define-method (update-measure-predicate (s <symbol>) (sys <system>))
  (let ((new (shallow-clone sys)))
    (slot-set! new 'measure-predicate s)
    new))

(define-method (update-measure-less-than (s <symbol>) (sys <system>))
  (let ((new (shallow-clone sys)))
    (slot-set! new 'measure-less-than s)
    new))

(define-method (update-definition (d <definition>) (sys <system>))
  (define (update d defs)
    (if (null? defs)
        (raise-exception
         (make-exception
          (make-exception-with-origin 'update-definition)
          (make-exception-with-message "not found")
          (make-exception-with-irritants (list d defs))))
        (if (equal? (get-name d) (get-name (car defs)))
            (cons d (cdr defs))
            (cons (car defs) (update d (cdr defs))))))
  (let ((new (shallow-clone sys)))
    (slot-set! new 'definitions
               (update d (get-definitions sys)))
    new))

(define-method (remove-first-definition (sys <system>))
  (let ((new (shallow-clone sys)))
    (slot-set! new 'definitions
               (cdr (get-definitions sys)))
    new))

(define-method (first-definition (sys <system>))
  (car (get-definitions sys)))

(define-method (system-empty? (sys <system>))
  (null? (get-definitions sys)))

(define-method (add-definition (d <definition>) (s <system>))
  (if (lookup (get-name d) s)
      (raise-exception
       (make-exception
        (make-exception-with-origin 'add-definition)
        (make-exception-with-message "duplicated definition")
        (make-exception-with-irritants (get-name d))))
      (if (reserved? (get-name d))
          (raise-exception
           (make-exception
            (make-exception-with-origin 'add-definition)
            (make-exception-with-message "reserved name")
            (make-exception-with-irritants (get-name d))))
          (let ((new (shallow-clone s)))
            (slot-set! new 'definitions
                       (cons d (get-definitions s)))
            new))))

(define-method (validate (d <definition>))
  (let* ((vars (get-variables d))
         (name (get-name d)))
    (validate-vars (format #f "~a" name) vars)))

(define-method (validate (d <expandable-function>))
  (let* ((vars (get-variables d))
         (name (get-name d))
         (expr (get-expression d)))
    (validate-expression name vars expr)
    (next-method)))

(define-method (validate (d <theorem*>))
  (let* ((vars (get-variables d))
         (name (get-name d))
         (expr (get-expression d)))
    (validate-expression name vars expr)
    (next-method)))

(define-syntax-rule (define/guard (name (var p?) ...) b b* ...)
  (define (name var ...)
    (unless (p? var)
      (error (format #f
                     "~a:~%  expected:  ~a~%  given: "
                     'name
                     'p?)
             var))
    ...
    b b* ...))

(define (natural? x)
  (and (exact-integer? x)
       (not (negative? x))))

(define (option p?)
  (lambda (x)
    (or (p? x) (not x))))

(define (list-of p?)
  (lambda (x)
    (and (list? x)
         (every p? x))))

(define (expression? expr)
  (cond ((expr-quoted? expr) #t)
        ((if-form? expr)
         (and (expression? (if-form-test expr))
              (expression? (if-form-then expr))
              (expression? (if-form-else expr))))
        ((app-form? expr)
         (and (symbol? (car expr))
              (list? (cdr expr))
              (every expression? (cdr expr))))
        ((variable? expr) #t)
        (else #f)))

(define (app-form? expr)
  (and (pair? expr)
       (not (eq? (car expr) 'quote))
       (not (eq? (car expr) 'if))))

(define (app-form name args)
  (cons name args))

(define (app-form-name expr)
  (car expr))

(define (app-form-args expr)
  (cdr expr))

(define (if-form test then else)
  (list 'if test then else))

(define (if-form? x)
  (and (pair? x)
       (eq? (car x) 'if)))

(define (if-form-test expr)
  (list-ref expr 1))

(define (if-form-then expr)
  (list-ref expr 2))

(define (if-form-else expr)
  (list-ref expr 3))

(define (expression-app-forms expr)
  (cond
   ((if-form? expr)
    (append-map expression-app-forms
                (list (if-form-test expr)
                      (if-form-then expr)
                      (if-form-else expr))))
   ((app-form? expr)
    (cons expr
          (append-map expression-app-forms
                      (app-form-args expr))))
   (else '())))

(define (expression-functions expr)
  (cond
   ((if-form? expr)
    (apply lset-union
           eq?
           (map expression-functions
                (list (if-form-test expr)
                      (if-form-then expr)
                      (if-form-else expr)))))
   ((app-form? expr)
    (cons (app-form-name expr)
          (apply lset-union
                 eq?
                 (map expression-functions (app-form-args expr)))))
   (else '())))

(define (expression-vars expr)
  (cond
   ((expr-quoted? expr) '())
   ((if-form? expr)
    (lset-union eq?
                (expression-vars (if-form-test expr))
                (expression-vars (if-form-then expr))
                (expression-vars (if-form-else expr))))
   ((app-form? expr)
    (apply lset-union
           eq?
           (map expression-vars (app-form-args expr))))
   ((variable? expr) (list expr))
   (else '())))

(define (expr-quoted? expr)
  (and (pair? expr)
       (eq? 'quote (car expr))
       (pair? (cdr expr))
       ((const #t) (car (cdr expr)))
       (null? (cdr (cdr expr)))))

(define (expr-unquote expr)
  (car (cdr expr)))

(define (expr-quote expr)
  (list 'quote expr))

(define (variable? x)
  (symbol? x))

(define (variable=? v1 v2)
  (eq? v1 v2))

(define-class <rule> ()
  (vars #:getter rule-vars #:init-keyword #:vars)
  (preconds #:getter rule-preconds #:init-keyword #:preconds)
  (lhs #:getter rule-lhs #:init-keyword #:lhs)
  (rhs #:getter rule-rhs #:init-keyword #:rhs))

(define (rule var preconds lhs rhs)
  (make <rule>
    #:vars var
    #:preconds preconds
    #:lhs lhs
    #:rhs rhs))

(define (rule? x)
  (is-a? x <rule>))

(define (binding? x)
  (and (pair? x)
       (symbol? (car x))
       (expression? (cdr x))))

(define (env? x)
  ((list-of binding?) x))

(define/guard (substitute (env env?) (expr (const #t)))
  (cond ((expr-quoted? expr) expr)
        ((pair? expr)
         (cons (substitute env (car expr))
               (substitute env (cdr expr))))
        ((assoc expr env) => cdr)
        (else expr)))

(define (match-rule preconds rl expr env)
  (define (fail)
    (shift k #f))
  (define (var? v)
    (and (member v (rule-vars rl))
         #t))
  (define (add-env var expr env)
    (cond
     ((assoc var env)
      => (match-lambda
           ((env-var . env-expr)
            (if (equal? env-expr expr)
                env
                (fail)))))
     (else
      (cons (cons var expr)
            env))))
  (define (mat-fold lhss exprs env)
    (cond ((and (pair? lhss) (pair? exprs))
           (mat-fold (cdr lhss)
                     (cdr exprs)
                     (mat (car lhss)
                          (car exprs)
                          env)))
          ((and (null? lhss) (null? exprs)) env)
          (else (fail))))
  (define (mat-begin lhs expr env)
    (reset (mat lhs expr env)))
  (define (mat lhs expr env)
    (cond ((expr-quoted? lhs)
           (if (expr-quoted? expr)
               (if (equal? lhs expr)
                   env
                   (fail))
               (fail)))
          ((and (if-form? lhs)
                (if-form? expr))
           (mat-fold (list (if-form-test lhs)
                           (if-form-then lhs)
                           (if-form-else lhs))
                     (list (if-form-test expr)
                           (if-form-then expr)
                           (if-form-else expr))
                     env))
          ((app-form? lhs)
           (if (and (app-form? expr)
                    (symbol? (app-form-name lhs))
                    (eqv? (app-form-name lhs) (app-form-name expr)))
               (mat-fold (app-form-args lhs) (app-form-args expr) env)
               (fail)))
          ((var? lhs) (add-env lhs expr env))
          (else (fail))))
  (define (mat-preconds rlps k+env)
    (if (null? rlps)
        k+env
        (mat-preconds
         (cdr rlps)
         (let search ((ps preconds))
           (if (null? ps)
               (shift k ((car k+env) #f))
               (let ((env (mat-begin (car rlps) (car ps) (cdr k+env))))
                 (cond
                  ((mat-begin (car rlps) (car ps) (cdr k+env))
                   => (lambda (env)
                        (shift k0
                               (reset
                                (or (shift k (k0 (cons k env)))
                                    (k0 (search (cdr ps))))))))
                  (else (search (cdr ps))))))))))
  (define (valid? env expr)
    (cond ((expr-quoted? expr) #t)
          ((pair? expr)
           (and (valid? env (car expr))
                (valid? env (cdr expr))))
          ((var? expr)
           (cond ((assoc expr env) => (const #t))
                 (else #f)))
          (else #t)))
  (reset
   (shift k0
          (match (mat-preconds (rule-preconds rl) (cons k0 env))
            ((k . env)
             (cond
              ((mat-begin (rule-lhs rl) expr env)
               => (lambda (env)
                    (if (valid? env (rule-rhs rl))
                        env
                        (k #f))))
              (else (k #f))))
            (else #f)))))

(define (apply-rule preconds rl expr env)
  (cond
   ((match-rule preconds rl expr env)
    => (cut substitute <> (rule-rhs rl)))
   (else #f)))

(define (code x)
  (list 'code x))

(define (code-expr x)
  (cadr x))

(define-class <mrule> ()
  (lhs #:getter mrule-lhs #:init-keyword #:lhs)
  (rhs #:getter mrule-rhs #:init-keyword #:rhs))

(define (mrule lhs rhs)
  (make <mrule> #:lhs lhs #:rhs rhs))

(define (mrule-vars mrl)
  (define (all-vars x)
    (cond ((expr-quoted? x) '())
          ((pair? x)
           (append (all-vars (car x))
                   (all-vars (cdr x))))
          ((variable? x) (list x))
          (else '())))
  (all-vars (mrule-lhs mrl)))

(define (macro name mrules literals)
  (make <macro>
    #:name name
    #:variables '()
    #:mrules mrules
    #:literals literals))

(define (apply-mrule rl ls expr)
  (define (literal? x)
    (member x ls))
  (define (var? v)
    (and (member v (mrule-vars rl))
         #t))
  (call/cc
   (lambda (k)
     (define (mat-map lhs-tree expr-tree env)
       (cond ((and (pair? lhs-tree)
                   (pair? expr-tree))
              (mat-map (car lhs-tree)
                       (car expr-tree)
                       (mat-map (cdr lhs-tree)
                                (cdr expr-tree)
                                env)))
             (else (mat lhs-tree expr-tree env))))
     (define (mat lhs expr env)
       (cond ((expr-quoted? lhs)
              (if (expr-quoted? expr)
                  (if (equal? lhs expr)
                      env
                      (k #f))
                  (k #f)))
             ((and (pair? lhs) (pair? expr))
              (mat-map lhs expr env))
             ((literal? lhs)
              (if (eq? lhs expr)
                  env
                  (k #f)))
             ((var? lhs)
              (cond
               ((assoc lhs env)
                => (match-lambda
                     ((env-var . env-expr)
                      (if (equal? env-expr expr)
                          env
                          (k #f)))))
               (else
                (cons (cons lhs expr)
                      env))))
             ((eqv? lhs expr) env)
             (else (k #f))))
     (define (mrule-substitute env expr)
       (cond ((expr-quoted? expr) expr)
             ((pair? expr)
              (cons (mrule-substitute env (car expr))
                    (mrule-substitute env (cdr expr))))
             ((literal? expr) expr)
             ((and (variable? expr) (assoc expr env)) => cdr)
             (else expr)))
     (mrule-substitute (mat (mrule-lhs rl)
                            expr
                            '())
                       (mrule-rhs rl)))))

(define (apply-macro m expr)
  (cond ((and (pair? expr)
              (eq? (get-name m) (car expr)))
         (let loop ((rs (macro-mrules m)))
           (cond ((null? rs)
                  (error "(vikalpa) macro fail" m expr))
                 ((apply-mrule (car rs) (macro-literals m) expr) => identity)
                 (else (loop (cdr rs))))))
        (else #f)))

(define (expand ms expr)
  (let loop ((ms ms)
             (expr expr))
    (cond
     ((null? ms) expr)
     (else
      (expand (cdr ms)
              (cond
               ((apply-macro (car ms) expr) => identity)
               (else expr)))))))

(define (expand* ms expr)
  (let loop ((ms ms)
             (expr expr))
    (let ((new-expr (expand ms expr)))
      (if (equal? expr new-expr)
          (if (and (not (expr-quoted? new-expr))
                   (pair? new-expr))
              (cons (expand* ms (car new-expr))
                    (expand* ms (cdr new-expr)))
              new-expr)
          (expand* ms new-expr)))))

(define (quote-all x)
  (cond
   ((null? x) x)
   ((expr-quoted? x) x)
   ((pair? x)
    (cons (quote-all (car x))
          (quote-all (cdr x))))
   ((symbol? x) x)
   (else `',x)))

(define (let? x)
  (and (list? x)
       (= 3 (length x))
       (eq? 'let (list-ref x 0))
       ((list-of (lambda (x)
                   (and (list? x)
                        (= 2 (length x))
                        (symbol? (car x)))))
        (list-ref x 1))))

(define (expand-let x)
  (define (let-substitute env expr)
    (cond ((expr-quoted? expr) expr)
          ((let? expr)
           (let-substitute
            (append (map (lambda (binding)
                           (cons (car binding)
                                 (let-substitute env
                                                 (cadr binding))))
                         (list-ref expr 1))
                    env)
            (list-ref expr 2)))
          ((pair? expr)
           (cons (let-substitute env (car expr))
                 (let-substitute env (cdr expr))))
          ((assoc expr env) => cdr)
          (else expr)))
  (cond
   ((expr-quoted? x) x)
   ((let? x)
    (expand-let
     (let-substitute (map (lambda (binding) (cons (car binding)
                                                  (cadr binding)))
                          (list-ref x 1))
                     (list-ref x 2))))
   ((pair? x)
    (cons (expand-let (car x))
          (expand-let (cdr x))))
   (else x)))

(define (convert-to-expression x)
  (quote-all
   (expand* (filter (cut is-a? <> <macro>)
                    (get-definitions (current-system)))
            (expand-let x))))

(define (vars? x)
  (and (list? x)
       (every variable? x)))

(define (theorem-rules x)
  (expression->rules (get-variables x)
                     '()
                     (get-expression x)))

(define (result? x)
  (or (result/error? x)
      (result/expr? x)))

(define (result/error? x)
  (and (pair? x)
       (eq? 'result/error (car x))))

(define (result/error . args)
  (cons* 'result/error args))

(define (result/expr? x)
  (and (list? x)
       (= 2 (length x))
       (eq? 'result/expr (car x))
       (expression? (cadr x))))

(define (result/expr x)
  (list 'result/expr x))

(define/guard (result/expr-expr (x result/expr?))
  (cadr x))

(define (rewrite/eval expr)
  (let eval ((result (result/expr expr)))
    (cond
     ((result/error? result) result)
     ((result/expr? result)
      (let ((expr (result/expr-expr result)))
        (cond
         ((expr-quoted? expr) (result/expr expr))
         ((app-form? expr)
          (let ((args/result (map (compose eval result/expr)
                                  (app-form-args expr)))
                (name (app-form-name expr)))
            (cond
             ((find error? args/result) => identity)
             ((lookup name (current-system))
              => (lambda (f)
                   (let ((args (map result/expr-expr args/result))
                         (gs (get-guards f))
                         (vars (get-variables f))
                         (form (defined-function-app-form f)))
                     (define (guard-ok? vars form g)
                       (let ((result (eval (apply-rule '()
                                                       (rule vars '() form g)
                                                       `(,name ,@args)
                                                       '()))))
                         (if (result/error? result)
                             result
                             (expr-unquote (result/expr-expr result)))))
                     (if (every (lambda (g) (guard-ok? vars form g)) gs)
                         (eval (rewrite1 `(,name ,@args)
                                         `(rewrite () ,name)))
                         (result/error 'guard-error `(,name ,@args) `(and ,@gs))))))
             (else (result/error 'function-not-found name)))))
         ((if-form? expr)
          (let ((test/result (eval (result/expr (if-form-test expr)))))
            (if (result/error? test/result)
                test/result
                (if (equal? (result/expr-expr test/result)
                            (false))
                    (eval (result/expr (if-form-else expr)))
                    (eval (result/expr (if-form-then expr)))))))
         ((variable? expr)
          (result/error 'eval 'variable-found expr))
         (else
          (result/error 'eval 'invalid-expression expr)))))
     (else (result/error 'eval 'invalid-result result)))))

(define (rewriter? x)
  (match x
    (('rewrite path command-name command-ops ...)
     (and (path? path)
          (command-name? command-name)
          (every command-option? command-ops)))
    (('eval path) (path? path))
    #;
    (('induction path (fname vars ...))
     (and (path? path)
          (symbol? fname)
          (every variable? vars)))
    (else #f)))

(define (sequence? x)
  (and (list? x)
       (every rewriter? x)))

(define (path? x)
  (and (list? x)
       (every natural? x)))

(define (command-name? x) #t)

(define (command-option? x)
  (and (pair? x)
       (case (car x)
         ((=) (and (list? x)
                    (= 3 (length x))
                    (variable? (list-ref x 1))
                    (expression? (list-ref x 2))))
         (else #f))))

(define (command-name x)
  (car x))

(define (command-options x)
  (cdr x))

(define/guard (system-eval (sys system?) (expr (const #t)))
  (parameterize ((current-system sys))
    (rewrite/eval (convert-to-expression expr))))

(define (extract path expr fail)
  (if (null? path)
      (values expr '() identity)
      (let ((i (car path)))
        (cond
         ((if-form? expr)
          (let ((precond (if-form-test expr)))
            (receive (extracted-expr preconds builder)
                (extract (cdr path) (list-ref expr i) fail)
              (values extracted-expr
                      (case i
                        ((1) preconds)
                        ((2) (cons (prop-not (prop-not precond))
                                   preconds))
                        ((3) (cons (prop-not precond) preconds))
                        (else (fail 'if-invaild-path path)))
                      (lambda (x)
                        (append (list-head expr i)
                                (list (builder x))
                                (list-tail expr (+ i 1))))))))
         ((< i (length expr))
          (receive (extracted-expr preconds builder)
              (extract (cdr path) (list-ref expr i) fail)
            (values extracted-expr
                    preconds
                    (lambda (x)
                      (append (list-head expr i)
                              (list (builder x))
                              (list-tail expr (+ i 1)))))))
         (else
          (fail 'invalid-path path))))))

(define (function->rules x)
  (list (rule (get-variables x)
              (list)
              (defined-function-app-form x)
              (get-expression x))
        (rule (get-variables x)
              (list)
              (get-expression x)
              (defined-function-app-form x))))

(define (apply-function f args)
  (apply-rule '()
              (rule (get-variables f)
                    '()
                    (defined-function-app-form f)
                    (get-expression f))
              (app-form (get-name f) args)
              '()))

(define (parse-options/theorem ops fail)
  (if (null? ops)
      (values '())
      (receive (env)
          (parse-options/theorem (cdr ops) fail)
        (case (caar ops)
          ((=)
           (let ((op (car ops)))
             (cons (cons (list-ref op 1)
                         (list-ref op 2))
                   env)))
          (else
           (fail 'invalid-option (car ops)))))))

(define (rewrite/theorem cmd-name cmd-ops thm preconds expr)
  (call/cc
   (lambda (k)
     (define (fail . args)
       (k (apply result/error args)))
     (receive (env)
         (parse-options/theorem cmd-ops fail)
       (cond
        ((any (cut apply-rule preconds <> expr env)
              (theorem-rules thm)) => result/expr)
        (else
         (result/error 'apply-theorem cmd-name expr)))))))

(define (rewrite/core-function f expr)
  (if (and (app-form? expr)
           (eq? (get-name f) (app-form-name expr))
           (= (length (get-variables f)) (length (app-form-args expr)))
           (every expr-quoted? (app-form-args expr)))
      (result/expr
       (expr-quote (apply (get-procedure f)
                          (map expr-unquote (app-form-args expr)))))
      (result/error 'apply-core-function (get-name f) expr)))

(define (rewrite/function fname f expr)
  (cond
   ((any (cut apply-rule '() <> expr '())
         (function->rules f))
    => result/expr)
   (else
    (result/error 'apply-function fname expr))))

(define (rewrite1 expr r)
  (call/cc
   (lambda (k)
     (define (fail . args)
       (k (apply result/error args)))
     (define (result->expr x)
       (cond
        ((result/error? x) (fail (cdr x)))
        (else
         (result/expr-expr x))))
     (match r
       (('eval path)
        (receive (extracted-expr preconds builder)
            (extract path expr fail)
          (result/expr
           (builder
            (result->expr (rewrite/eval extracted-expr))))))
       #;
       (('induction path (fname vars ...))
        (receive (extracted-expr preconds builder)
            (extract path expr fail)
          (result/expr
           (builder
            (result->expr
             (rewrite/induction sys fname vars preconds extracted-expr))))))
       (('rewrite path cmd-name cmd-ops ...)
        (receive (extracted-expr preconds builder)
            (extract path expr fail)
          (result/expr
           (builder
            (result->expr
             (cond
              ((lookup cmd-name (current-system))
               => (lambda (x)
                    (cond
                     ((is-a? x <core-function>)
                      (rewrite/core-function x extracted-expr))
                     ((is-a? x <theorem*>)
                      (rewrite/theorem cmd-name cmd-ops x preconds extracted-expr))
                     ((is-a? x <expandable-function>)
                      (rewrite/function cmd-name x extracted-expr))
                     (else
                      (result/error 'invalid-command cmd-name extracted-expr)))))
              (else (result/error 'command-not-found cmd-name extracted-expr))))))))))))

(define (rewrite expr seq)
  (let loop ((result (result/expr expr))
             (seq seq))
    (cond
     ((result/error? result) result)
     ((result/expr? result)
      (if (null? seq)
          result
          (loop (rewrite1 (result/expr-expr result)
                          (car seq))
                (cdr seq))))
     (else (result/error 'invalid-result result)))))

(define (expr-not x)
  (list 'not x))

(define (prop-not x)
  (match x
    (('not ('not expr)) (prop-not expr))
    (('not expr) expr)
    (expr (expr-not expr))))

(define (expr-equal? x)
  (and (list? x)
       (= 3 (length x))
       (eq? (get-equal-symbol (current-system)) (list-ref x 0))
       (expression? (list-ref x 1))
       (expression? (list-ref x 2))))

(define (expr-equal-lhs x)
  (list-ref x 1))

(define (expr-equal-rhs x)
  (list-ref x 2))

(define (expression->rules vars preconds expr)
  (if (if-form? expr)
      (append (expression->rules vars
                                 (cons (prop-not
                                        (prop-not
                                         (if-form-test expr)))
                                       preconds)
                                 (if-form-then expr))
              (expression->rules vars
                                 (cons (prop-not (if-form-test expr))
                                       preconds)
                                 (if-form-else expr))
              (expression->rules vars
                                 preconds
                                 (if-form-test expr)))
      (if (expr-equal? expr)
          (list (rule vars
                      preconds
                      (expr-equal-lhs expr)
                      (expr-equal-rhs expr))
                (rule vars
                      preconds
                      (expr-equal-rhs expr)
                      (expr-equal-lhs expr)))
          '())))

(define current-system (make-parameter (make <system>)))
(define reserved-symbols '(quote let if error))
(define (reserved? x)
  (member x reserved-symbols))

(define-syntax define-axiom
  (syntax-rules ()
    ((_ name (var ...) expr)
     (let ((t (make <axiom>
                #:name 'name
                #:variables '(var ...)
                #:expression (convert-to-expression 'expr))))
       (current-system (add-definition t (current-system)))
       (validate t)
       t))))

(define-syntax define-theorem
  (syntax-rules ()
    ((_ name (var ...) expr)
     (match 'name
       (`(guard . ,_)
        (raise-exception (make-exception
                          (make-exception-with-origin "define-theorem")
                          (make-exception-with-message "invalid theorem name (guard _ ...)")
                          (make-exception-with-irritants 'name))))
       (else
        (let ((t (make <conjecture>
                   #:name 'name
                   #:variables '(var ...)
                   #:expression (convert-to-expression 'expr))))
          (current-system (add-definition t (current-system)))
          (validate t)
          t))))))

(define (add-guard-theorem name)
  (cond
   ((lookup name (current-system))
    => (lambda (f)
         (if (is-a? f <expandable-function>)
             (add-definition (make <conjecture>
                               #:name `(guard ,name)
                               #:variables (get-variables f)
                               #:expression (fold smart-implies
                                                  (make-guard-claim
                                                   (get-expression f))
                                                  (get-guards f)))
                             (current-system))
             (raise-exception
              (make-exception
               (make-exception-with-origin 'define-guard-theorem)
               (make-exception-with-message "not expandable function")
               (make-exception-with-irritants name))))))
   (else
    (raise-exception
              (make-exception
               (make-exception-with-origin 'define-guard-theorem)
               (make-exception-with-message "not found")
               (make-exception-with-irritants name))))))

(define-syntax define-guard-theorem
  (syntax-rules ()
    ((_ name)
     (current-system (add-guard-theorem 'name)))))

(define-syntax define-core-function/guard
  (syntax-rules (and)
    ((_ name (var ...) (and guard ...) proc)
     (let ((f (make <core-function>
                #:name 'name
                #:variables '(var ...)
                #:guards (map convert-to-expression (list 'guard ...))
                #:procedure proc)))
       (current-system (add-definition f (current-system)))
       (validate f)
       f))
    ((_ name (var ...) guard proc)
     (define-core-function/guard name (var ...) (and guard) proc))))

(define-syntax define-core-function
  (syntax-rules ()
    ((_ name (var ...) proc)
     (define-core-function/guard name (var ...) (and) proc))))

(define (recursive? f)
  (member (get-name f) (expression-functions (get-expression f))))

(define-syntax define-function/guard
  (syntax-rules (and)
    ((_ name (var ...) (and guard-expr ...) expr)
     (let* ((expression (convert-to-expression 'expr))
            (guard-expressions (map convert-to-expression
                                    (list 'guard-expr ...)))
            (f (make <function>
                 #:name 'name
                 #:variables '(var ...)
                 #:guards guard-expressions
                 #:expression expression
                 #:code (code 'expr))))
       (current-system (add-definition f (current-system)))
       (validate f)
       (when (not (recursive? f))
         (let ((g (make <total-function>
                    #:name (get-name f)
                    #:variables (get-variables f)
                    #:guards (get-guards f)
                    #:expression (get-expression f)
                    #:code (get-code f)
                    #:claim (true)
                    #:proof '())))
           (current-system (update-definition g (current-system)))
           (validate g)))
       ))
    ((_ name (var ...) guard expr)
     (define-function/guard name (var ...) (and guard) expr))))

(define-syntax define-function
  (syntax-rules ()
    ((_ name (var ...) expr)
     (define-function/guard name (var ...) (and) expr))))

(define-syntax define-syntax-rules
  (syntax-rules ()
    ((_ name (l ...) ((lhs1 . lhs2) rhs) ...)
     (let ((m (macro 'name
                (list (mrule '(lhs1 . lhs2) 'rhs)
                      ...)
                '(l ...))))
       (current-system (add-definition m (current-system)))
       m))))

(define-syntax admit
  (syntax-rules (and)
    ((_ name)
     (cond
      ((lookup 'name (current-system))
       => (lambda (d)
            (unless (or (is-a? d <conjecture>)
                        (is-a? d <function>))
              (raise-exception
               (make-exception
                (make-exception-with-origin 'name)
                (make-exception-with-message "not provable definition")
                (make-exception-with-irritants 'name))))
            (let ((g (if (is-a? d <conjecture>)
                         (make <admitted-theorem>
                           #:name (get-name d)
                           #:variables (get-variables d)
                           #:expression (get-expression d)
                           #:claim (true)
                           #:proof '())
                         (make <admitted-function>
                           #:name (get-name d)
                           #:variables (get-variables d)
                           #:guards (get-guards d)
                           #:expression (get-expression d)
                           #:code (get-code d)
                           #:claim (true)
                           #:proof '()))))
              (validate g)
              (current-system (update-definition g (current-system))))))
      (else
       (raise-exception
        (make-exception
         (make-exception-with-origin 'name)
         (make-exception-with-message "not found")
         (make-exception-with-irritants 'name))))))))

(define (core-system)
  (parameterize ((current-system (make <system>)))
    (define-syntax-rules and ()
      ((and) '#t)
      ((and x) x)
      ((and x . xs) (if x (and . xs) #f)))
    (define-core-function not (x) not)
    (define-core-function equal? (x y) equal?)
    (current-system)))

(define (core-system/equal-t-nil)
  (parameterize ((current-system (make <system>
                                   #:equal-symbol 'equal
                                   #:true-object ''t
                                   #:false-object ''nil)))
    (define-syntax-rules and ()
      ((and) 't)
      ((and x) x)
      ((and x . xs) (if x (and . xs) 'nil)))
    (define-core-function equal (x y) (lambda (x y)
                                        (if (equal? x y)
                                            't
                                            'nil)))
    (define-core-function not (x)
      (lambda (x)
        (if (eq? x 'nil)
            't
            'nil)))
    (current-system)))

(define-syntax define-system
  (syntax-rules ()
    ((_ name (system) expr ...)
     (begin
       (define (name)
         (when (equal? 'name 'system)
           (raise-exception
            (make-exception
             (make-exception-with-origin 'name)
             (make-exception-with-message "recursive system")
             (make-exception-with-irritants 'system))))
         (parameterize
             ((current-system (system)))
           expr
           ...
           (current-system)))
       (let ((result (system-check (name))))
         (unless (null? result)
           (pretty-print result)))))))

(define (validate-function-name desc name)
  (define (err)
    (raise-exception
     (make-exception
      (make-exception-with-origin 'desc)
      (make-exception-with-message "unbound function")
      (make-exception-with-irritants name))))
  (cond
   ((lookup name (current-system))
    => (lambda (f)
         (if (is-a? f <function*>)
             name
             (err))))
   (else (err))))

(define-syntax set-measure-predicate
  (syntax-rules ()
    ((_ name)
     (begin
       (validate-function-name 'set-measure-predicate 'name)
       (current-system (update-measure-predicate 'name (current-system)))))))

(define-syntax set-measure-less-than
  (syntax-rules ()
    ((_ name)
     (begin
       (validate-function-name 'set-measure-less-than 'name)
       (current-system
        (update-measure-less-than 'name (current-system)))))))

(define (defined-function-app-form f)
  (app-form (get-name f) (get-variables f)))

(define (single? x)
  (and (pair? x)
       (null? (cdr x))))

(define (smart-if x y z)
  (cond
   ((equal? y z) y)
   ((equal? x (true)) y)
   ((equal? x (false)) z)
   (else `(if ,x ,y ,z))))

(define (smart-and . args)
  (cond
   ((null? args) (true))
   ((equal? (true) (car args)) (apply smart-and (cdr args)))
   (else
    (let ((rest (apply smart-and (cdr args))))
      (if (equal? (true) rest)
          (car args)
          (smart-if (car args)
                    rest
                    (false)))))))

(define (smart-implies x y)
  (cond
   ((equal? (false) x) (true))
   ((equal? (true) y) (true))
   (else
    (smart-if x y (true)))))

(define (make-totality-claim* m-expr f)
  (let* ((name (get-name f)))
    (define (convert app-form)
      (cond
       ((apply-rule '()
                    (rule (get-variables f)
                          '()
                          (defined-function-app-form f)
                          m-expr)
                    app-form
                    '())
        => identity)
       (else (error "make-totality-claim: convert error"
                    (get-name f)
                    m-expr
                    app-form))))
    (smart-if `(,(get-measure-predicate (current-system)) ,m-expr)
              (let loop ((expr (get-expression f)))
                (cond
                 ((expr-quoted? expr) (true))
                 ((variable? expr) (true))
                 ((if-form? expr)
                  (let ((test/result (loop (if-form-test expr)))
                        (then/result (loop (if-form-then expr)))
                        (else/result (loop (if-form-else expr))))
                    (smart-and test/result
                               (smart-if (if-form-test expr)
                                         then/result
                                         else/result))))
                 ((app-form? expr)
                  (let ((rest
                         (let f ((args (app-form-args expr)))
                           (cond ((null? args) (true))
                                 ((single? args) (loop (car args)))
                                 (else (smart-and (loop (car args))
                                                  (f (cdr args))))))))
                    (if (eq? name (app-form-name expr))
                        (smart-and `(,(get-measure-less-than (current-system))
                                     ,(convert expr)
                                     ,m-expr)
                                   rest)
                        rest)))
                 (else (error "(vikalpa) make-totality-claim: error"
                              (get-name f)
                              m-expr))))
              (false))))

(define (make-guard-claim expr)
  (define (find-preconds expr)
    (cond
     ((app-form? expr)
      (let ((rest (append-map find-preconds (cdr expr))))
        (append (cond ((lookup (car expr) (current-system)) =>
                       (lambda (f)
                         (let ((preconds (get-guards f)))
                           (map (lambda (precond)
                                  (substitute (map cons
                                                   (get-variables f)
                                                   (cdr expr))
                                              precond))
                                preconds))))
                      (else (error "make-guard-claim: error" (car expr))))
                rest)))
     ((if-form? expr)
      (find-preconds (if-form-test expr)))
     (else '())))
  (define (build/find-if expr)
    (cond
     ((if-form? expr)
      (smart-if (build/find-if (if-form-test expr))
                (build (if-form-then expr))
                (build (if-form-else expr))))
     ((app-form? expr)
      (apply smart-and (map build/find-if (app-form-args expr))))
     (else (true))))
  (define (build expr)
    (cond
     ((if-form? expr)
      (apply smart-and
             (append (find-preconds (if-form-test expr))
                     (list (smart-if (if-form-test expr)
                                     (build (if-form-then expr))
                                     (build (if-form-else expr)))))))
     ((app-form? expr)
      (apply smart-and
             (append (find-preconds expr)
                     (list (build/find-if expr)))))
     (else (true))))
  (build expr))

(define (make-induction-claim f vars c)
  (unless (is-a? f <expandable-function>)
    (raise-exception
     (make-exception
      (make-exception-with-origin 'define-proof)
      (make-exception-with-message
       "measure function must be expandable function")
      (make-exception-with-irritants (get-name f)))))
  (define (find-app-forms expr)
    (cond
     ((app-form? expr)
      (let ((rest (append-map find-app-forms (cdr expr))))
        (if (eq? (get-name f) (app-form-name expr))
            (cons expr rest)
            rest)))
     ((if-form? expr)
      (error "make-induction-claim(find-app-forms): not supported"
             expr))
     (else '())))
  (define (prop form)
    (cond
     ((apply-rule '()
                  (rule vars
                        '()
                        (app-form (get-name f) vars)
                        c)
                  form
                  '())
      => identity)
     (else
      (error "make-induction-claim: fail" app-form))))
  (cond
   ((apply-function f vars)
    => (lambda (expr)
         (let build ((expr expr))
           (cond
            ((if-form? expr)
             (let ((app-forms (find-app-forms (if-form-test expr))))
               (smart-implies (if (null? app-forms)
                                  (true)
                                  (fold smart-implies
                                        c
                                        (map prop app-forms)))
                              (smart-if (if-form-test expr)
                                        (build (if-form-then expr))
                                        (build (if-form-else expr))))))
            (else
             (let ((app-forms (find-app-forms expr)))
               (fold smart-implies c (map prop app-forms))))))))
   (else (error "make-induction-claim: invalid"
                f vars c))))

(define (validate-sequence d seq)
  (for-each (lambda (r)
              (match r
                (('rewrite _ _ . command-ops)
                 (for-each (lambda (x)
                             (match x
                               (('= var expr)
                                (validate-expression 
                                                     `(define-proof ,(get-name d))
                                                     (get-variables d)
                                                     expr))
                               (else #f)))
                           command-ops))
                (else #f)))
            seq))

(define (add-proof/function f seed seq)
  (define (update-claim claim)
    (update-definition (make <total-function>
                         #:name (get-name f)
                         #:variables (get-variables f)
                         #:guards (get-guards f)
                         #:expression (get-expression f)
                         #:code (get-code f)
                         #:claim claim
                         #:proof seq)
                       (current-system)))
  (validate-sequence f seq)
  (if seed
      (begin
        (validate-expression `(defien-proof ,(get-name f))
                             (get-variables f)
                             seed)
        (update-claim
         (fold smart-implies
               (make-totality-claim* seed f)
               (get-guards f))))
      (raise-exception
       (make-exception
        (make-exception-with-origin 'define-proof)
        (make-exception-with-message "need measure expression")
        (make-exception-with-irritants (get-expression f))))))

(define (add-proof/theorem t seed seq)
  (define (seed-error m)
    (raise-exception
     (make-exception
      (make-exception-with-origin 'define-proof)
      (make-exception-with-message (string-append "invalid seed: " m))
      (make-exception-with-irritants (list (get-name t) seed)))))
  (validate-sequence t seq)
  (let ((claim
         (if seed
             (match seed
               ((fname vars ...)
                (cond
                 ((lookup fname (current-system))
                  => (cut make-induction-claim <> vars (get-expression t)))
                 (else (seed-error "function not found"))))
               (else (seed-error "format error")))
             (get-expression t))))
    (update-definition (make <theorem>
                         #:name (get-name t)
                         #:variables (get-variables t)
                         #:expression (get-expression t)
                         #:claim claim
                         #:proof seq)
                       (current-system))))

(define (add-proof name seed seq)
  (cond
   ((not (sequence? seq))
    (raise-exception
     (make-exception
      (make-exception-with-origin 'define-proof)
      (make-exception-with-message "not sequence")
      (make-exception-with-irritants seq))))
   ((lookup name (current-system))
    => (lambda (def)
         (current-system
          (if (and (is-a? def <provable>)
                   (not (is-a? def <proved>)))
              (cond
               ((is-a? def <function>)
                (add-proof/function def seed seq))
               ((is-a? def <conjecture>)
                (add-proof/theorem def seed seq))
               (else
                (raise-exception
                 (make-exception
                  (make-exception-with-origin 'define-proof)
                  (make-exception-with-message "error")
                  (make-exception-with-irritants def)))))
              (raise-exception
               (make-exception
                (make-exception-with-origin 'define-proof)
                (make-exception-with-message "not provable definition")
                (make-exception-with-irritants def)))))))
   (else
    (raise-exception
     (make-exception
      (make-exception-with-origin 'define-proof)
      (make-exception-with-message "definition is not found")
      (make-exception-with-irritants name))))))

(define-syntax define-proof
  (syntax-rules ()
    ((_ name
        seed
        seq)
     (add-proof 'name
                'seed
                'seq))
    ((_ name seq)
     (define-proof name #f seq))))

(define (validate-expression/error name vars expr)
  (with-exception-handler
      (lambda (e)
        (if (eq? 'validate-expression/error (exception-origin e))
            `(error ,name ,vars ,expr))
        (raise-exception e))
    (lambda ()
      (validate-expression 'validate-expression/error vars expr)
      #f)))

(define (validate-expression name vars expr)
  (let* ((expr-fnames (expression-functions expr))
         (expr-vars (expression-vars expr))
         (expr-app-forms (expression-app-forms expr)))
    (define (err msg x)
      (raise-exception
       (make-exception
        (make-exception-with-origin name)
        (make-exception-with-message msg)
        (make-exception-with-irritants x))))
    (for-each (lambda (x)
                (when (member x expr-fnames)
                  (err "invalid variable" x)))
              vars)
    (for-each (lambda (fname)
                (unless (cond
                         ((lookup fname (current-system)) =>
                          (lambda (f)
                            (for-each
                             (lambda (app-form)
                               (when (equal? fname (app-form-name app-form))
                                 (unless (= (length (get-variables f))
                                            (length (app-form-args app-form)))
                                   (err (format
                                         #f
                                         "~a :wrong number of arguments ~s"
                                         (get-name f)
                                         (get-variables f))
                                        (app-form-args app-form)))))
                             expr-app-forms)
                            #t))
                         (else #f))
                  (err "undefined function" fname)))
              expr-fnames)
    (for-each (lambda (x)
                (unless (member x vars)
                  (err "undefined variable" x)))
              expr-vars)))

(define (dup? xs)
  (if (null? xs)
      #f
      (if (member (car xs) (cdr xs))
          #t
          (dup? (cdr xs)))))

(define (validate-vars desc vars)
  (define (err)
    (raise-exception
     (make-exception
      (make-exception-with-message
       (string-append "(vikalpa) " desc ": duplicated variable"))
      (make-exception-with-irritants vars))))
  (when (dup? vars)
    (err)))

(define-method (get-type (s <axiom>)) 'axiom)
(define-method (get-type (s <theorem>)) 'theorem)
(define-method (get-type (s <conjecture>)) 'conjecture)
(define-method (get-type (s <core-function>)) 'core-function)
(define-method (get-type (s <function>)) 'function)
(define-method (get-type (s <total-function>)) 'total-function)
(define-method (get-type (s <admitted-function>)) 'admitted-function)
(define-method (get-type (s <admitted-theorem>)) 'admitted-theorem)
(define-method (get-type (s <macro>)) 'macro)

(define-method (show (d <macro>))
  (list (get-type d)))
(define-method (show (d <theorem*>))
  (list (get-type d)
        (get-variables d)
        (get-expression d)))
(define-method (show (d <core-function>))
  (list (get-type d)
        (get-variables d)))
(define-method (show (d <expandable-function>))
  (list (get-type d)
        (get-variables d)
        (get-expression d)))
(define-method (show (d <admitted-function>))
  (list (get-type d)
        (get-variables d)
        (get-expression d)))

(define* (system-apropos sys str)
  (pretty-print
   (filter-map (lambda (d)
                 (let ((name (format #f "~a" (get-name d))))
                   (if (string-match (string-append ".*"
                                                    (regexp-quote str)
                                                    ".*")
                                     name)
                       (list (get-name d) (show d))
                       #f)))
               (get-definitions sys))))

(define (system-check/guard)
  (filter-map (lambda (f)
                (if (lookup `(guard ,(get-name f)) (current-system))
                    #f
                    (if (equal? (make-guard-claim (get-expression f))
                                (true))
                        #f
                        `((guard ,(get-name f))
                          (add (define-guard-theorem ,(get-name f)))))))
              (filter (cut is-a? <> <expandable-function>)
                      (get-definitions (current-system)))))

(define (system-check sys)
  (append
   (parameterize ((current-system sys))
     (system-check/guard))
   (let loop ((sys sys)
              (fails '()))
     (if (system-empty? sys)
         fails
         (let ((d (first-definition sys))
               (sys-without-first (remove-first-definition sys)))
           (define* (next #:optional fail)
             (loop sys-without-first
                   (if fail
                       (cons fail fails)
                       fails)))
           (cond
            ((is-a? d <proved>)
             (let ((result
                    (if (is-a? d <theorem>)
                        (parameterize ((current-system sys-without-first))
                          (rewrite (get-claim d)
                                   (get-proof d)))
                        (parameterize ((current-system sys))
                          (rewrite (get-claim d)
                                   (get-proof d))))))
               (cond
                ((equal? result
                         (parameterize ((current-system sys))
                           (result/expr (true))))
                 (next))
                (else
                 (next (list (get-name d) result))))))
            ((is-a? d <provable>)
             (next (list (get-name d))))
            (else (next))))))))

(define (system? x)
  (is-a? x <system>))

(define/guard (system-lookup (sys system?) (name (const #t)))
  (cond
   ((lookup name sys) => show)
   (else #f)))

(define/guard (system-rewrite (sys system?) (expr (const #t)) (seq sequence?))
  (parameterize ((current-system sys))
    (rewrite (convert-to-expression expr) seq)))