Codebase list cafeobj / dd54cec1-0dda-4c8f-ba98-0d7ff40e468a/main thstuff / cexec.lisp
dd54cec1-0dda-4c8f-ba98-0d7ff40e468a/main

Tree @dd54cec1-0dda-4c8f-ba98-0d7ff40e468a/main (Download .tar.gz)

cexec.lisp @dd54cec1-0dda-4c8f-ba98-0d7ff40e468a/mainraw · history · blame

   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
;;;-*-Mode:LISP; Package: CHAOS; Base:10; Syntax:Common-lisp -*-
;;;
;;; Copyright (c) 2000-2018, Toshimi Sawada. All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;;   * Redistributions of source code must retain the above copyright
;;;     notice, this list of conditions and the following disclaimer.
;;;
;;;   * Redistributions in binary form must reproduce the above
;;;     copyright notice, this list of conditions and the following
;;;     disclaimer in the documentation and/or other materials
;;;     provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
(in-package :chaos)
#|=============================================================================
                               System:CHAOS
                              Module:thstuff
                             File:cexec.lisp
=============================================================================|#
#-(or :chaos-debug SBCL)
(declaim (optimize (speed 3) (safety 0) #-GCL (debug 0)))
#+:chaos-debug
(declaim (optimize (speed 1) (safety 3) #-GCL (debug 3)))

;;;
(declaim (special $$cexec-term))        ; the target term

;;; *****
;;; RULEs
;;; *****

;;; RULE-PAT
;;; - a rule applicable to the current target
;;; - POS: position matching 
;;; - RULE: the rule
;;; - SUBST: the substitution
;;;
(defstruct (rule-pat (:print-function print-rule-pattern))
  (pos nil :type list)                  ; matched position (list of fixnum)
  (rule nil :type rewrite-rule)         ; matched rule
  (subst nil :type substitution)        ; variable substitution
  (cond-ok t :type (or null t))         ; t iff condition part of the rule is satisfied
  (condition nil :type (or null term))  ; resulting condition part ('if') when cond-ok = nil
  (num 0 :type fixnum)                  ; sequential #, used for debugging
  )

(declaim (type fixnum .rules-so-far.))
(defvar .rules-so-far. 0)

(defun print-rule-pattern (rpat &optional (stream *standard-output*) &rest ignore)
  (declare (type rule-pat rpat)
           (type stream stream)
           (ignore ignore))
  (format stream "~%-- rule pattern: ~d" (rule-pat-num rpat))
  (format stream "~%  posisition: ~a" (rule-pat-pos rpat))
  (format stream "~&  rule      :")(print-chaos-object (rule-pat-rule rpat))
  (format stream "~&  subst     :")(print-substitution (rule-pat-subst rpat))
  (format stream "~&  cond-ok   :~a" (rule-pat-cond-ok rpat))
  (let ((cond (rule-pat-condition rpat)))
    (when cond
      (format stream "~&  condition :")(term-print cond))))

;;; *****
;;; STATE
;;; *****

;;; RWL-STATE
;;; represents a state
;;;
(defstruct (rwl-state
            (:print-function pr-rwl-state))
  (state 0 :type fixnum)                      ; fixnum value identifying this state
  (term nil :type term)                       ; a term
  (trans-rules nil :type list)                ; applicable rules to this state
  (rule-pat nil :type (or null rule-pat))     ; the rule-pat which derived this state
  (subst nil :type list)                      ; list of substitution !!
  (is-final nil :type (or t null))            ; t iff the state is a final state
  (loop nil :type (or t null))                ; t iff the same state occurs more than once
  (condition nil)                             ;
  (depth 0 :type fixnum)                      ; nesting depth of rwl-search*
  )

(declaim (inline state-is-valid-transition))
(defun state-is-valid-transition (state)
  (declare (type rwl-state state)
           (optimize (speed 3) (safety 0)))
  (let ((cond (rwl-state-condition state)))
    (and (not (rwl-state-loop state))
         (or (null cond)
             (is-true? cond)))))

(defun pr-rwl-state (state &optional (stream *standard-output*) &rest ignore)
  (declare (type rwl-state state)
           (type stream stream)
           (ignore ignore))
  (let ((*standard-output* stream))
    (format t "#<rwl-state(~D):" (rwl-state-state state))
    (term-print (rwl-state-term state))
    (princ ", ")
    (dolist (sub (rwl-state-subst state))
      (print-substitution sub))
    (when (rwl-state-is-final state)
      (princ " ,final"))
    (princ ">")))

(declaim (special .rwl-search-depth.)
         (type fixnum .rwl-search-depth.))
(defvar .rwl-search-depth. -1)

(defun print-rwl-state (state &optional (stream *standard-output*) &rest ignore)
  (declare (ignore ignore)
           (type rwl-state state)
           (type stream stream))
  (let ((*standard-output* stream))
    (format t "~%[state ~D-~D] " (rwl-state-depth state) (rwl-state-state state))
    (let ((*print-indent* (+ 4 *print-indent*)))
      (term-print-with-sort (rwl-state-term state))
      (when *cexec-trace*
        (format t "~& matched with the substitution "))
      (let ((*print-indent* (+ 4 *print-indent*)))
        (dolist (subst (rwl-state-subst state))
          (print-next)
          (print-substitution subst)))
      (flush-all))))

(defun print-state-transition (state sub-states &optional (stream *standard-output*))
  (declare (type rwl-state state)
           (type list sub-states)
           (type stream stream))
  (let ((*standard-output* stream)
        (arc-num 0))
    (declare (type fixnum arc-num))
    (format t "~%[state ~D-~D] " (rwl-state-depth state) (rwl-state-state state))
    (term-print-with-sort (rwl-state-term state))
    (dolist (sub sub-states)
      (format t "~&  arc ~D --> [state ~D-~D] " arc-num (rwl-state-depth state) (rwl-state-state sub))
      (let ((*print-indent* (+ 4 *print-indent*)))
        (print-next)
        (print-axiom-brief (rule-pat-rule (rwl-state-rule-pat sub))))
      (incf arc-num))))

;;; ***********
;;; SEARCH TREE
;;; ***********

;;; Search tree
;;; - bi-directional dag (see comlib/dag.lisp)
;;; - datum contains an instance of rwl-state.
;;; 
(defstruct (rwl-sch-node (:include bdag)
            (:conc-name "SCH-NODE-")
            (:print-function pr-rwl-sch-node))
  (done nil :type (or null t))          ; t iff this node is checked already
  (is-solution nil :type (or null t))   ; t iff this node found as a solution
  )

(defmacro create-sch-node (rwl-state)
  `(make-rwl-sch-node :datum ,rwl-state :subnodes nil :parent nil :is-solution nil))

(defun pr-rwl-sch-node (node &optional (stream *standard-output*) &rest ignore)
  (declare (ignore ignore))
  (let ((*standard-output* stream))
    (format t "SCH-NODE:~A" (dag-node-datum node))))

;;; **************
;;; SEARCH CONTEXT
;;; **************

;;; RWL-SCH-CONTEXT
;;; 
(defstruct (rwl-sch-context
            (:print-function print-sch-context))
  (module nil :type module)                   ; context module
  (term nil :type term)                       ; initial term
  (pattern nil :type term)                    ; pattern to be matched
  (condition nil :type (or null term))        ; =(*)=> with COND
  (zero-trans-allowed nil :type (or null t))  ; ... =>*
  (final-check nil :type (or null t))         ; ... =>!
  (max-sol most-positive-fixnum :type fixnum) ; =(max-sol, )=>
  (sol-found 0 :type fixnum)                  ; found solutions so far
  (max-depth most-positive-fixnum :type fixnum)
                                        ; =(, max-depth)=>
  (cur-depth 0 :type fixnum)            ; current depth
  (root nil :type (or null rwl-sch-node)) ; root node of the search tree
                                        ;   (an instance of rwl-sch-node) 
  (trans-so-far 0 :type fixnum)         ; # of transitions so far
  (last-siblings nil :type list)        ; nodes to be checked
                                        ; initially, this contains the root.
  (state-predicate nil)                 ; STATE equality predicate
  (answers nil :type list)              ; list of STATEs satisfying specified
                                        ; conditions.
  (bind nil)                            ; ....
  (if nil)                              ;
  (pr-out? nil :type (or null t))       ;
  (term-hash nil :type simple-vector)   ; term hash table for catching loop
  )

(defun print-sch-context (ctxt &optional (stream *standard-output*) &rest ignore)
  (declare (type rwl-sch-context ctxt)
           (type stream stream)
           (ignore ignore))
  (let ((*standard-output* stream)
        (mod (rwl-sch-context-module ctxt)))
    (with-in-module (mod)
      (format t "~%<< sch context >>")
      (format t "~%   module: ")
      (print-chaos-object (rwl-sch-context-module ctxt))
      (format t "~%   term: ")
      (term-print-with-sort (rwl-sch-context-term ctxt))
      (format t "~%   pattern: ")
      (term-print-with-sort (rwl-sch-context-pattern ctxt))
      (format t "~%   condition: ")
      (if (rwl-sch-context-condition ctxt)
          (term-print-with-sort (rwl-sch-context-condition ctxt))
        (princ "None."))
      (format t "~%   zero?: ~A" (rwl-sch-context-zero-trans-allowed ctxt))
      (format t "~%   final?: ~A" (rwl-sch-context-final-check ctxt))
      (format t "~%   max sol. : ~D" (rwl-sch-context-max-sol ctxt))
      (format t "~%   solutions: ~D" (rwl-sch-context-sol-found ctxt))
      (format t "~%   max depth: ~D" (rwl-sch-context-max-depth ctxt))
      (format t "~%   current depth: ~D" (rwl-sch-context-cur-depth ctxt))
      (format t "~%   root node: ~A" (rwl-sch-context-root ctxt))
      ;; (format t "~%   states: ~D" (rwl-sch-context-states-so-far ctxt))
      (format t "~%   transitions: ~D" (rwl-sch-context-trans-so-far ctxt))
      (format t "~%   last siblings: ")
      (dolist (s (rwl-sch-context-last-siblings ctxt))
        (format t "~%     ~A" s))
      (format t "~%   answers: ")
      (dolist (x (reverse (rwl-sch-context-answers ctxt)))
        (term-print-with-sort (rwl-state-term x)))
      (when (rwl-sch-context-bind ctxt)
        (format t "~%   bind pattern: ")
        (term-print-with-sort (rwl-sch-context-bind ctxt)))
      (when (rwl-sch-context-if ctxt)
        (format t "~%   if: ")
        (term-print-with-sort (rwl-sch-context-if ctxt))))))


;;; ******************
;;; RWL-SCH-NODE utils
;;; ******************

;;; print the rule & state
;;;
(defun show-rwl-sch-state (dag &optional (path? t) (bind-pattern nil))
  (declare (type rwl-sch-node dag))
  (let* ((st (dag-node-datum dag))
         (term (rwl-state-term st))
         (rule-pat (rwl-state-rule-pat st))
         (rl (if rule-pat (rule-pat-rule rule-pat)
               nil)))
    (when (and rl path?)
      (print-next)
      (princ "  ")
      (let ((*print-indent* (+ 8 *print-indent*)))
        (print-chaos-object rl) ; (print-axiom-brief rl)
        ))
    (format t "~%[state ~D-~D] " (rwl-state-depth st) (rwl-state-state st))
    (term-print-with-sort term)
    (dolist (sub (rwl-state-subst st))
      (format t "~&    ")
      (print-substitution sub)
      (when bind-pattern
        (let ((bimage (substitution-image-simplifying sub bind-pattern)))
          (normalize-term bimage)
          (format t "~%    => ")
          (term-print-with-sort bimage))))))

;;; print the label of a rule which derived a state
;;; that denode contains.
;;;
(defun show-rwl-sch-label (dnode)
  (declare (type rwl-sch-node dnode))
  (let* ((dt (dag-node-datum dnode))
         (rl (rule-pat-rule (rwl-state-rule-pat dt)))
         (label (car (rule-labels rl))))
    (if label
        (format t "~&[~a]" label)
      (format t "~&NONE"))))


;;; RULE PAT constructor
(defun make-rule-pat-with-check (pos rule subst sch-context)
  (declare (type list pos)
           (type rewrite-rule rule)
           (type substitution subst)
           (type rwl-sch-context sch-context)
           (optimize (speed 3) (safety 0)))
  (when (rule-non-exec rule)
    ;; the rule is marked as non-executable
    (return-from make-rule-pat-with-check nil))
  (let ((condition (rule-condition rule)))
    (declare (type term condition))
    ;; pre check whether the condition part is satisfied or not
    (when (and (is-true? condition)
               (null (rule-id-condition rule)))
      ;; rule is not conditional
      (return-from make-rule-pat-with-check
        (make-rule-pat :pos pos :rule rule :subst subst :num (incf .rules-so-far.))))
    ;; check the condition
    (let (($$term nil)
          ($$cond (set-term-color (substitution-image-cp subst condition))))
      (when *cexec-debug*
        (format t "~%rule: cond ") (term-print-with-sort $$cond)
        (format t "~%      subst") (print-substitution subst)
        (let ((vars (term-variables $$cond)))
          (dolist (v vars)
            (format t "~% var ") (term-print-with-sort v))))
      (catch 'rule-failure
        (if (and (or (null (rule-id-condition rule))
                     (rule-eval-id-condition subst
                                             (rule-id-condition rule)
                                             :slow))
                 (is-true? (progn (normalize-term $$cond) $$cond)))
            ;; the condition is satisfied
            (return-from make-rule-pat-with-check 
              (make-rule-pat :pos pos :rule rule :subst subst :cond-ok t :condition $$cond :num (incf .rules-so-far.)))
          (if (rwl-sch-context-if sch-context)
              ;; rule condition fail & there exists 'if'
              (return-from make-rule-pat-with-check
                (make-rule-pat :pos pos :rule rule :subst subst :cond-ok nil :condition $$cond :num (incf .rules-so-far.)))
            (return-from make-rule-pat-with-check nil))))
      nil)))

(defun rule-pat-equal (pat1 pat2)
  (declare (type rule-pat pat1 pat2)
           (optimize (speed 3) (safety 0)))
  (and (equal (rule-pat-pos pat1) (rule-pat-pos pat2))
       (eq (rule-pat-rule pat1) (rule-pat-rule pat2))
       (substitution-equal (rule-pat-subst pat1) (rule-pat-subst pat2))))


;;; *********************
;;; SEARCH CONTEXT UTILS
;;; *********************

;;; parse-depth&state
;;;
(defun parse-depth&state (&optional ds-string)
  (unless ds-string
    (return-from parse-depth&state nil))
  (let* ((ds-list (parse-with-delimiter ds-string #\-))
         (depth (or (and (cdr ds-list) (read-from-string (car ds-list)))
                    0))
         (state (or (and (cdr ds-list) (read-from-string (cadr ds-list)))
                    (read-from-string (car ds-list)))))
    (unless (and (integerp depth) (>= depth 0)
                 (integerp state) (>= state 0))
      (with-output-chaos-error ('invalid-depth-state)
        (format t "Invalid depth/state specifier: ~a" ds-string)))
    (list depth state)))

;;; show-rwl-sch-graph
;;;
(defun show-rwl-sch-graph (&optional num)
  (let ((c-num (if num
                   (read-from-string num)
                 0))
        (sch-context nil))
    (unless (integerp c-num)
      (with-output-chaos-error ('invalid-context-number)
        (format t "invalid search graph number ~s" num)))
    (setq sch-context (nth c-num (reverse .rwl-context-stack.)))
    (unless sch-context
      (with-output-chaos-error ('no-such-context)
        (format t "no such search graph ~d" num)))
    (let ((mod (rwl-sch-context-module sch-context))
          (root (rwl-sch-context-root sch-context)))
      (unless mod
        (with-output-chaos-error ('no-context)
          (format t "no context module...")))
      (unless root
        (with-output-chaos-error ('no-root)
          (format t "no search result exists...")))
      (when (and *current-module*
                 (not (eq *current-module* mod)))
        (with-output-chaos-warning ()
          (format t "the context(module) of search graph is different from the current module.")))
      ;;
      (with-in-module (mod)
        (let ((state-hash (make-hash-table)))
          (dag-wfs root
                   #'(lambda (d)
                       (let* ((state-node (dag-node-datum d))
                              (state (rwl-state-state state-node)))
                         (unless (gethash state state-hash)
                           (setf (gethash state state-hash) t)
                           (print-state-transition
                            state-node
                            (mapcar #'(lambda (sd)
                                        (dag-node-datum sd))
                                    (dag-node-subnodes d))))))))))))

(defun find-rwl-sch-state (num &optional (sch-context .rwl-sch-context.))
  (declare (type fixnum num))
  (unless sch-context
    (with-output-chaos-error ('no-root-node)
      (format t "no search result exists")))
  (let ((dag nil))
    (setq dag
      (catch 'dag-found
        (dag-wfs (rwl-sch-context-root sch-context)
                 #'(lambda (d)
                     (let ((st (dag-node-datum d)))
                       (when (= (rwl-state-state st) num)
                         (throw 'dag-found d)))))
        nil))
    dag))

(defun find-rwl-sch-state-globally (num)
  (declare (type fixnum num))
  (dolist (context .rwl-context-stack.)
    (let ((st (find-rwl-sch-state num context)))
      (when st (return-from find-rwl-sch-state-globally (values context st))))))

(defun show-rwl-sch-path (&optional (ds-string nil)
                                    (label? nil)
                                    (state-only? nil))

  (unless ds-string
    (return-from show-rwl-sch-path
      (format t "~%Nothing to be reported...")))
  (unless .rwl-context-stack.
    (with-output-chaos-error ('no-context)
      (format t "~%There is no search context.")))
  (let* ((ds-list (parse-depth&state ds-string))
         (sch-context (or (nth (car ds-list) (reverse .rwl-context-stack.))
                          (with-output-chaos-error ('no-sch-context)
                            (format t "There is no RWL search context ~d" (car ds-list)))))
         (dag (find-rwl-sch-state (cadr ds-list) sch-context)))
    (unless dag
      (with-output-chaos-error ('no-such-state)
        (format t "There is no state ~d in context ~d" (cadr ds-list) (car ds-list))))
    (let ((mod (rwl-sch-context-module sch-context)))
      (when (and *current-module*
                 (not (eq *current-module* mod)))
        (with-output-chaos-warning ()
          (format t "the context(module) of search result is different from the current module.")))
      (with-in-module (mod)
        (cond (state-only? (show-rwl-sch-state dag nil (rwl-sch-context-bind sch-context)))
              (t (let ((parents (get-bdag-parents dag)))
                   (cond (label?
                          (dolist (p (cdr parents)) ;root has no transition
                            (show-rwl-sch-label p))
                          (show-rwl-sch-label dag))
                         (t (dolist (p parents)
                              (show-rwl-sch-state p t (rwl-sch-context-bind sch-context)))
                            (show-rwl-sch-state dag t (rwl-sch-context-bind sch-context)))))))))))

;;; ******************
;;; SOME UTILs on TERM
;;; ******************
;;; returns a subterm at position 'pos'
;;;
(declaim (inline get-target-subterm))
(defun get-target-subterm (term pos)
  (declare (type term term)
           (type list pos)
           (optimize (speed 3) (safety 0)))
  (let ((cur term))
    (declare (type term cur))
    (when pos
      (dolist (p pos)
        (declare (type fixnum p))
        (setq cur (term-arg-n cur p))
        (unless cur
          (with-output-panic-message ()
            (format t "could not find subterm at pos ~d" pos)
            (format t "~% target was ")
            (term-print term)
            (break "wow!")
            (chaos-error 'panic)))))
    cur))

;;; *************
;;; PATTERN MATCH
;;; *************

;;; finds all transition rules possibly applicable to the given target term
;;;
(defun find-matching-rules-for-exec (target sch-context &optional start-pos)
  (declare (type term target)
           (type rwl-sch-context sch-context)
           (type list start-pos)
           (optimize (speed 3) (safety 0)))
  (let ((module (rwl-sch-context-module sch-context)))
    (declare (type module module))
    (when start-pos
      (setq target (get-target-subterm target start-pos)))
    (with-in-module (module)
      (let* ((*module-all-rules-every* t)
             (rules (get-module-axioms *current-module* t))
             (rls nil)
             (res nil))
        (declare (type list res))
        (dolist (rule rules)
          (declare (type rewrite-rule rule))
          (when (rule-is-rule rule)
            (push rule rls)))
        ;; gather rules
        (setq res (find-matching-rules-for-exec* target rls start-pos sch-context))
        (setq res (delete-duplicates res
                                     :test #'rule-pat-equal))
        (when *cexec-debug*
          (format t "~%** ~D rules were found for term: "
                  (length res))
          (term-print target)
          (terpri)
          (dolist (r res)
            (print-rule-pattern r)))
        res ))))

(defun find-matching-rules-for-exec* (target rules pos sch-context)
  (declare (type term target)
           (type list rules pos)
           (type rwl-sch-context sch-context))
  (when *cexec-debug*
    (format t "~%find matching rules. ")
    (term-print target)
    (terpri))
  (if (term-is-application-form? target)
      (let ((res nil)
            (rule-pat nil))
        (do* ((rls rules (cdr rls))
              (rule (car rls) (car rls)))
            ((endp rls))
          (let* ((patterns nil)
                 (lhs (rule-lhs rule))
                 (head (if (term-is-variable? lhs)
                           nil
                         (term-head lhs))))
            (push rule patterns)
            ;; ------- apply-rule always applies extensions
            (when head
              (when (method-is-associative head)
                (if (method-is-commutative head)
                    (let ((ac-ext (give-AC-extension rule)))
                      (when ac-ext
                        (unless (car ac-ext)
                          (print ac-ext)
                          (break "Here it is!"))
                        (push (car ac-ext) patterns)))
                  ;;
                  (let ((a-exts (give-A-extensions rule)))
                    (dolist (r a-exts)
                      (when r
                        (push r patterns)))))))
            ;; ------------
            (dolist (pat patterns)
              (block next
                (unless pat (break "HANA my"))
                ;; find all possible subst
                (multiple-value-bind (gs sub no-match eeq)
                    (@matcher (axiom-lhs pat) target :match)
                  (declare (ignore eeq))
                  (when no-match (return-from next))
                  (setq rule-pat (make-rule-pat-with-check pos pat sub sch-context))
                  (when rule-pat
                    (push rule-pat res))
                  (loop
                    (multiple-value-setq (gs sub no-match)
                      (next-match gs))
                    (when no-match (return-from next))
                    (setq rule-pat (make-rule-pat-with-check pos pat sub sch-context))
                    (when rule-pat
                      (push rule-pat res))))))
            ))                          ; done for all rules
        ;; recursively find rules for subterms
        (dotimes (x (length (term-subterms target)))
          (let ((r (find-matching-rules-for-exec* (term-arg-n target x)
                                                  rules
                                                  (append pos (list x))
                                                  sch-context)))
            (when r (setq res (nconc res r)))))
        ;;
        res)
    nil))

;;; ****************
;;; SOLUTION CHECKER
;;; ****************

(declaim (inline if-binding-should-be-printe))
(defun if-binding-should-be-printed (sch-context)
  (declare (type rwl-sch-context sch-context)
           (optimize (speed 3) (safety 0)))
  (and (rwl-sch-context-if sch-context)
       (<= (rwl-sch-context-cur-depth sch-context) (rwl-sch-context-max-depth sch-context))))

;;; 
(declaim (inline print-subst-if-binding-result))
(defun print-subst-if-binding-result (state sub sch-context)
  (declare (ignore state)
           (optimize (speed 3) (safety 0)))
  (setf (rwl-sch-context-pr-out? sch-context) t)
  (print-next)
  (format t "    ") (print-substitution sub)
  (when (rwl-sch-context-bind sch-context)
    (let ((bimg (substitution-image-simplifying sub (rwl-sch-context-bind sch-context))))
      (normalize-term bimg)
      (print-next)
      (format t "    --> ")
      (if (and *grind-bool-term*
               (sort= (term-sort bimg) *bool-sort*))
          (let ((bt (abstract-boolean-term bimg *current-module*)))
            (print-bterm-grinding bt))
        (term-print-with-sort bimg)))))

;;; rwl-sch-check-conditions (node rwl-sch-context)
;;; check if the given state matches to the target pattern.
;;; return t iff matches, otherwise nil.
;;;
(defun rwl-sch-check-conditions (node sch-context)
  (declare (type rwl-sch-node node)
           (type rwl-sch-context sch-context)
           (optimize (speed 3) (safety 0)))
  (flet ((condition-check-ok (subst)
           (let ((cond (rwl-sch-context-condition sch-context))
                 ($$term nil)
                 ($$cond nil)
                 (*rewrite-exec-mode* (if *rewrite-exec-condition*
                                          *rewrite-exec-mode*
                                        nil)))
             (if (null cond)
                 (setq $$cond *bool-true*)
               (setq $$cond (set-term-color
                             (substitution-image-cp subst cond))))
             (when *cexec-debug*
               (format t "~%  subst     :") (print-substitution subst)
               (format t "~&  suchThat  :") (term-print $$cond))
             (or (is-true? $$cond)
                 (is-true? (progn
                             (if *cexec-debug*
                                 (let (($$trace-rewrite t))
                                   (print-term-tree $$cond t)
                                   (normalize-term $$cond))
                               (normalize-term $$cond))
                             (when *cexec-debug*
                               (format t " -C-> ") (term-print $$cond)
                               (format t "~% = ~s" (is-true? $$cond)))
                             $$cond))))))
    ;; if checked already, we return immediately as non.
    (when (and (sch-node-done node) (null (rwl-sch-context-if sch-context)))
      (return-from rwl-sch-check-conditions nil))
    ;;
    (let* ((state (dag-node-datum node))
           (if-var (rwl-sch-context-if sch-context))
           (rule-pat (rwl-state-rule-pat state)))
      (declare (type rwl-state state))

      (when *chaos-verbose*
        (format t " ~D-~D" (rwl-state-depth state) (rwl-state-state state)))

      (setf (sch-node-done node) t)     ; mark checked already

      (when *cexec-debug* 
        (when (rwl-sch-context-condition sch-context)
          (format t "~%** check condition ")
          (term-print-with-sort (rwl-sch-context-condition sch-context))
          (if rule-pat
              (print-rule-pattern rule-pat)
            (format t "~% no rule-pat."))))
      ;; 0 transition?
      (when (and (not (rwl-sch-context-zero-trans-allowed sch-context))
                 (= 0 (rwl-sch-context-trans-so-far sch-context)))
        (when *cexec-debug*
          (format t "~%.check condition return with 0 transition."))
        (return-from rwl-sch-check-conditions nil))
      ;; check with target pattern.
      (multiple-value-bind (gs sub no-match eeq)
          (@matcher (rwl-sch-context-pattern sch-context)
                    (rwl-state-term state)
                    :match)
        (declare (ignore eeq))
        (when no-match
          (when *cexec-debug*
            (format t "~%.check condition return with no-match."))
          (return-from rwl-sch-check-conditions nil))
        ;; expand subst with 
        (let ((rule-subst (and rule-pat (rule-pat-subst rule-pat))))
          (when (car rule-subst)
            (setq sub (append sub rule-subst))))
        ;; additionaly expand subst 'if' part bindings
        (when if-var
          (setq sub (substitution-add sub if-var (or (rwl-state-condition state)
                                                     *bool-true*))))
        (when (condition-check-ok sub)
          (when (if-binding-should-be-printed sch-context) ; if-var
            (pr-used-rule state)
            (print-subst-if-binding-result state sub sch-context))
          (when (state-is-valid-transition state)
            (push sub (rwl-state-subst state))))
        ;; try other patterns untill there's no hope
        (loop
          (multiple-value-setq (gs sub no-match)
            (next-match gs))
          (when no-match (return))
          ;; expand subst with 
          (let ((rule-subst (and rule-pat (rule-pat-subst rule-pat))))
            (when (car rule-subst)
              (setq sub (append sub rule-subst))))
          (when if-var
            (setq sub (substitution-add sub if-var (or (rwl-state-condition state)
                                                       *bool-true*))))
          (when (condition-check-ok sub)
            (when (if-binding-should-be-printed sch-context) ; if-var
              (when (pr-used-rule state)
                (print-subst-if-binding-result state sub sch-context)))
            (when (state-is-valid-transition state)
              (push sub (rwl-state-subst state))))))
      (not (null (rwl-state-subst state))))))

(defun pr-used-rule (state)
  (declare (type rwl-state state))
  (let ((rule-pat (rwl-state-rule-pat state))
        (rule nil))
    (unless rule-pat (return-from pr-used-rule nil))
    (setq rule (rule-pat-rule rule-pat))
    (unless *print-exec-rule*
      (when (member (axiom-kind rule) .ext-rule-kinds.)
        (return-from pr-used-rule nil)))
    (unless *rwl-search-no-state-report*
      (format t "~%=> ")
      (print-axiom-brief rule))
    t))

;;; *********
;;; TERM HASH : used for loop check
;;; *********
(defvar .cexec-term-hash. nil)
;; (deftype term-hash-key () '(unsigned-byte 29))
(deftype term-hash-key () 'fixnum)
#+(or (and :SBCL :64-BIT) (and :ALLEGRO :64BIT))
(defconstant term-hash-mask #x1FFFFFFFFFFFFFF)
#+(or (and :SBCL :32-BIT) (and :ALLEGRO :32BIT))
(defconstant term-hash-mask #x1FFFFFFF)
#-(or :SBCL :ALLEGRO)
(defconstant term-hash-mask #x1FFFFFFF)

(defconstant term-hash-size 9001)

(declaim (inline term-hash-equal))
#-CMU
(defun term-hash-equal (x)
  (declare (optimize (speed 3) (safety 0)))
  (logand term-hash-mask (sxhash x)))

#+CMU
(defun term-hash-equal (x)
  (sxhash x))

(declaim (inline term-hash-eq))
(defun term-hash-eq (object)
  (declare (optimize (speed 3) (safety 0)))
  (ash (+ (the term-hash-key
	    (logand term-hash-mask
		    (the fixnum (addr-of object))))
	  3)
       -3))

(declaim (inline term-hash-comb))
(defun term-hash-comb (x y)
  (declare (optimize (speed 3) (safety 0))
           (type fixnum x y))
  (the term-hash-key (logand term-hash-mask (logand term-hash-mask (+ x y)))))

(defun cexec-hash-term (term)
  (declare (type term term)
           (optimize (speed 3) (safety 0)))
  (cond ((term-is-applform? term)
         (let ((res (sxhash (the symbol (method-id-symbol (term-head term))))))
           (dolist (subterm (term-subterms term))
             (setq res (term-hash-comb res (cexec-hash-term subterm))))
           res))
        ((term-is-builtin-constant? term)
         (term-hash-comb (sxhash (the symbol (sort-id (term-sort term))))
                         (term-hash-equal (term-builtin-value term))))
        ((term-is-variable? term) (term-hash-eq term))))

; (defun dump-cexec-term-hash (&optional (size term-hash-size))
;   (let ((mod (get-context-module)))
;     (unless mod (return-from dump-cexec-term-hash nil))
;     (with-in-module (mod)
;       (dotimes (x size)
;         (let ((ent (svref .cexec-term-hash. x)))
;           (when ent
;             (format t "~%[~3d]: ~d entrie(s)" x (length ent))
;             (dotimes (y (length ent))
;               (let ((e (nth y ent)))
;                 (format t "~%(~d)" y)
;                 (let ((*print-indent* (+ 2 *print-indent*)))
;                   (term-print (car e))
;                   (print-next)
;                   (princ "==>")
;                   (print-next)
;                   (term-print (cdr e)))))))))))

(defun dump-cexec-term-hash (&optional (size term-hash-size))
  (let ((mod (get-context-module)))
    (unless mod (return-from dump-cexec-term-hash nil))
    (with-in-module (mod)
      (dotimes (x size)
        (let ((ent (svref .cexec-term-hash. x)))
          (when ent
            (format t "~%[~3d]: ~d entrie(s)" x (length ent))
            (dotimes (y (length ent))
              (let ((e (nth y ent)))
                (format t "~%(~d) " y) 
                (term-print (car e))
                (print-next)
                (princ "==> ")
                (princ (cdr e))))))))))

(declaim (inline get-sch-hashed-term))
(defun  get-sch-hashed-term (term term-hash)
  (declare (type term term)
           (type simple-vector term-hash)
           (optimize (speed 3) (safety 0)))
 (let ((val (cexec-hash-term term)))
   (let* ((ent (svref term-hash
                      (mod val term-hash-size)))
          (val (cdr (assoc term ent :test #'term-equational-equal))))
     (when val (incf (the fixnum *term-memo-hash-hit*)))
     val)))

(declaim (inline set-sch-hashed-term))
(defun set-sch-hashed-term (term term-hash value)
  (declare (type term term)
           (type simple-vector term-hash)
           (type fixnum value)
           (optimize (speed 3) (safety 0)))
  (let ((val (cexec-hash-term term)))
    (let ((ind (mod val term-hash-size)))
      (let ((ent (svref term-hash ind)))
        (let ((pr (assoc term ent :test #'term-equational-equal)))
          (if pr (rplacd pr value)
            (setf (svref term-hash ind) (cons (cons term value) ent))))))))

(defmacro cexec-get-hashed-term (term)
  `(get-sch-hashed-term ,term .cexec-term-hash.))

(defmacro cexec-set-hashed-term (term state-num)
  `(set-sch-hashed-term ,term .cexec-term-hash. ,state-num))

(declaim (inline cexec-sch-check-predicate))
(defun cexec-sch-check-predicate (term t1 pred-pat)
  (declare (type term term t1)
           (type list pred-pat)
           (optimize (speed 3) (safety 0)))
  (let ((pred (car pred-pat))
        (vars (cdr pred-pat))
        (subst nil)
        (res nil))
    (declare (type term pred)
             (type list vars))
    ;; make substittion
    (if (sort<= (term-sort term) (term-sort (the term (car vars))) *current-sort-order*)
        (push (cons (car vars) term) subst)
      (with-output-chaos-error ('invalid-state)
        (format t "withStateEq: sort of term does not match with variable:")
        (format t "~%  variable: ")
        (term-print-with-sort (car vars))
        (format t "~%  term:  ")
        (term-print-with-sort term)))
    (if (sort<= (term-sort term) (term-sort (cadr vars)) *current-sort-order*)
        (push (cons (cadr vars) t1) subst)
      (with-output-chaos-error ('invalid-state)
        (format t "withStateEq: sort of term does not match with variable:")
        (format t "~%  variable: ")
        (term-print-with-sort (cadr vars))
        (format t "~%  term: ")
        (term-print-with-sort t1)))
      
    ;; apply subst with coping pred
    ;; then reduce
    (setq res
      (is-true?
       (let (($$cond (set-term-color
                      (substitution-image-cp subst pred)))
             (*rewrite-exec-mode*
              (if *rewrite-exec-condition*
                  *rewrite-exec-mode*
                nil)))
         (when *cexec-debug* 
           (format t "~%[withEQ] ")
           (term-print $$cond))
         (normalize-term $$cond)
         (when *cexec-debug*
           (format t "~% = ")
           (term-print $$cond))
         $$cond)))
    (when (and res *cexec-trace*)
      (format t "~%** state predicate returned `true'."))
    res))

(defun cexec-loop-check (term sch-context)
  (declare (type term)
           (type rwl-sch-context sch-context)
           (optimize (speed 3) (safety 0)))
  (or (get-sch-hashed-term term .cexec-term-hash.)
      (let ((pred-pat (rwl-sch-context-state-predicate sch-context)))
        (if pred-pat
            (dotimes (x term-hash-size nil)
              (declare (fixnum x))
              (let ((entry (svref .cexec-term-hash. x)))
                (when entry
                  (dotimes (y (length entry))
                    (declare (type fixnum y))
                    (let ((t1 (nth y entry)))
                      (when (cexec-sch-check-predicate term (car t1) pred-pat)
                        (return-from cexec-loop-check (cdr t1))))))))
          nil))))

;;; 
;;; MAKE-RWL-STATE-WITH-HASH
;;;
(defun make-rwl-state-with-hash (target rule-pat sch-context)
  (declare (type term target)
           (type rule-pat rule-pat)
           (type rwl-sch-context sch-context)
           (optimize (speed 3) (safety 0)))
  (let* ((ostate-num (cexec-loop-check target sch-context))
         (condition (rule-pat-condition rule-pat))
         (new-state nil))
    (declare (type (or null fixnum) ostate-num))
    (cond (ostate-num
           ;; this means the same state has alredy been generated
           ;; from a node other than this node.
           ;; we create brand new state with the same state number
           (setq new-state (make-rwl-state :state ostate-num
                                           :term  target
                                           :rule-pat  rule-pat
                                           :subst  nil
                                           :condition condition
                                           :depth .rwl-search-depth.))
           (when (or *cexec-trace* *chaos-verbose*)
             (format t "~%* loop"))
           (setf (rwl-state-loop new-state) t))
          (t  (let ((state-num (incf .rwl-states-so-far.)))
                (setq new-state (make-rwl-state :state state-num
                                                :term  target
                                                :rule-pat  rule-pat
                                                :subst  nil
                                                :condition  condition
                                                :depth .rwl-search-depth.))
                ;; register the term
                (when *cexec-debug*
                  (format t "~%** hashing state ~D" state-num))
                (set-sch-hashed-term target .cexec-term-hash. state-num))))
    ;;
    new-state))

;;; *******************
;;; ONE STEP TRANSITION
;;; *******************

;;; RWL-STATE-SET-TRANSITION-RULES
;;;
(defun rwl-state-set-transition-rules (state sch-context)
  (declare (type rwl-state state)
           (type rwl-sch-context sch-context)
           (optimize (speed 3) (safety 0)))
  (let ((rule-pats (find-matching-rules-for-exec (rwl-state-term state) sch-context)))
    (setf (rwl-state-trans-rules state) rule-pats)
    (unless rule-pats
      (setf (rwl-state-is-final state) t))))

;;;
;;; APPLY-RULE-CEXEC: rule target -> Bool
;;;
(defun apply-rule-cexec (rule term subst)
  (declare (type rewrite-rule rule)
           (term term)
           (substitution subst))
  (catch 'rule-failure
    (progn
      (term-replace-dd-simple
       term
       (set-term-color
        (substitution-image-simplifying subst
                                        (rule-rhs rule)
                                        (rule-need-copy rule)
                                        :slow)))
      (return-from apply-rule-cexec t)))
  nil)

;;; CEXEC-TERM-1 (state-as-dag)
;;;
;;; - compute all possible transitions from the given state(an instance of
;;;   rwl-sch-node).
;;; - returns the list of substates which derived from the given state.
;;; - NOTE: term of the given state is NOT modified.
;;;
(defun cexec-term-1 (dag sch-context)   ; node-num ...
  (declare (type rwl-sch-node dag)
           (type rwl-sch-context sch-context)
           (optimize (speed 3) (safety 0)))
  (let* ((state (dag-node-datum dag))
         (term (rwl-state-term state)))
    (declare (type rwl-state state)
             (type term term))
    (flet ((no-more-transition ()
             (when (or *cexec-trace* *chaos-verbose*)
               (when (and (term-is-applform? term)
                          (method-has-trans-rule (term-head term)))
                 (with-output-simple-msg ()
                   (format t "-- no more transitions from state ~D-~D."
                           (rwl-state-depth state)
                           (rwl-state-state state)))))
             (setf (rwl-state-is-final state) t)
             nil)
           (exec-trace-form ()
             (format t "=(~a,~a)=>~a"
                     (if (= (rwl-sch-context-max-sol sch-context)
                            most-positive-fixnum)
                         "*"
                       (rwl-sch-context-max-sol sch-context))
                     (rwl-sch-context-cur-depth sch-context)
                     (if (rwl-sch-context-final-check sch-context)
                         "!"
                       (if (rwl-sch-context-zero-trans-allowed sch-context)
                           "*"
                         "+"))))
           (state-is-valid? (state)
             (let ((cond (rwl-state-condition state)))
               (or (null cond) (is-true? cond)))))
      ;;
      (unless (state-is-valid? state)
        (return-from cexec-term-1 nil))
      ;;
      (let ((xterm term)
            (ptrans? (dag-node-subnodes dag)))
        (when *cexec-debug*
          (format t "~%[cexec-term-1] target = ")
          (let ((*fancy-print* nil))
            (term-print-with-sort xterm))
          (flush-all))
        ;; already computed ..
        (when ptrans? (return-from cexec-term-1 ptrans?))
        ;;
        ;; apply all rules found
        ;;
        (let ((rule-pats (rwl-state-trans-rules state))
              (*rewrite-exec-mode* t)
              (sub-states nil)
              (real-pats nil))
          (setq real-pats (remove-if #'(lambda (x) (not (rule-pat-cond-ok x))) rule-pats))
          (when *cexec-debug*
            (format t "~%++ ~D rule patterns for state" (length rule-pats))
            (pr-rwl-state state))
          (when *chaos-verbose*
            (format t "~%-- from [state ~D-~D] "
                    (rwl-state-depth state)
                    (rwl-state-state state))
            (format t "~D possible transitions....."
                    (length real-pats)))
          ;;
          (unless rule-pats
            ;; no rules
            (no-more-transition)
            (return-from cexec-term-1 nil))
          ;; 
          (when *cexec-trace*
            (flush-all)
            (format t "~%~%**> Step ~D from [state ~D-~D] "
                    (rwl-sch-context-cur-depth sch-context)
                    (rwl-state-depth state)
                    (rwl-state-state state))
            (term-print-with-sort (rwl-state-term state))
            (flush-all))
          ;; apply all possible rules
          (do* ((rls rule-pats (cdr rls))
                (rule-pat (car rls) (car rls)))
              ((null rule-pat))
            (let* ((target-whole (simple-copy-term xterm))
                   (target (get-target-subterm target-whole
                                               (rule-pat-pos rule-pat))))
              (declare (type term target-whole)
                       (type term target))
              ;; the following should be done iff the target is NOT
              ;; in hash table + register target in hash.
              (when (apply-rule-cexec (rule-pat-rule rule-pat)
                                      target
                                      (rule-pat-subst rule-pat))
                (incf (rwl-sch-context-trans-so-far sch-context))
                (when *cexec-normalize*
                  (when *cexec-debug*
                    (format t "~%.. start doing normalization because cexec normalize is on.~%  -- ")
                    (term-print target-whole))
                  (let ((*rewrite-exec-mode* nil)
                        (xterm (if (and *cexec-trace* *chaos-verbose*)
                                   (simple-copy-term target-whole)
                                 nil)))
                    (mark-term-as-not-lowest-parsed target-whole)
                    (reset-reduced-flag target-whole)
                    (rewrite* target-whole)
                    (when *cexec-debug*
                      (format t "~&==> ")
                      (term-print target-whole))
                    (when xterm
                      (print-next)
                      (unless (term-equational-equal xterm target-whole)
                        (flush-all)
                        (let ((*fancy-print* nil)
                              (*print-indent* (+ 4 *print-indent*)))
                          (princ "> pre normalization : ")
                          (term-print xterm)
                          (print-next)
                          (princ "== ")
                          (term-print target-whole))
                        (flush-all)))))
                (let ((sub-state (make-rwl-state-with-hash target-whole
                                                           rule-pat
                                                           sch-context)))
                  (declare (type rwl-state sub-state))
                  (when sub-state
                    (when *cexec-debug*
                      (format t "~%** used rule pat = ~d" (rule-pat-num rule-pat)))
                    (when *cexec-trace*
                      (print-next)
                      (flush-all)
                      (let ((*fancy-print* nil)
                            (*print-indent* (+ 4 *print-indent*)))
                        (format t "@[~{~d~^ ~}]" (mapcar #'1+ (rule-pat-pos rule-pat)))
                        (exec-trace-form)
                        (format t " [state ~D-~D] " (rwl-state-depth sub-state) (rwl-state-state sub-state))
                        (term-print-with-sort target-whole)
                        (print-next)
                        (print-axiom-brief (rule-pat-rule rule-pat))
                        (print-next)
                        (print-substitution (rule-pat-subst rule-pat))) ; ***
                      (flush-all))
                    (push sub-state sub-states)))))) ; done apply all rules
          (if sub-states
              (progn
                (when *chaos-verbose*
                  (format t " => ~D (new) states."
                          (length sub-states) ))
                sub-states)
            (progn
              ;; for some unknown reason, no real transitions happened...
              (no-more-transition)
              nil)))))))

;;; RWL-STEP-FORWARD-1
;;; given a rwl-sch-context, execute one step transition for
;;; each `last-siblings' & check if derived terms match to `pattern'.
;;;
(defun rwl-step-forward-1 (sch-context)
  (declare (type rwl-sch-context sch-context)
           (optimize (speed 3) (safety 0)))
  ;; check # of transitions
  (when (>= (rwl-sch-context-trans-so-far sch-context)
            *cexec-limit*)
    (return-from rwl-step-forward-1 (values :max-transitions nil)))
  ;;
  (let ((to-do (rwl-sch-context-last-siblings sch-context))
        (found? nil))
    (when *chaos-verbose*
      (format t "~%-- ~D state(s) to be examined --" (length to-do)))
    ;;
    ;; 1. check for each state if it satisfies the target conditions
    ;;
    (when *chaos-verbose*
      (format t "~&.....condition check for each state.....~%"))
    (loop
      (unless to-do (return nil))       ; done for every state
      (block :continue
        (let ((node (pop to-do)))
          (declare (type rwl-sch-node node))
          ;;
          (when (sch-node-done node)
            ;; already checked 
            (return-from :continue nil))
          ;;
          (let ((state (dag-node-datum node)))
            ;; first prepare applicable rules for the next transition,
            ;; this also marks the state `is-final' iff there are no rules.
            (rwl-state-set-transition-rules state sch-context)
            ;; check state
            (when (and (rwl-sch-context-final-check sch-context)
                       (not (rwl-state-is-final state)))
              (return-from :continue nil)) ; skip this node
            ;;
            (when (rwl-sch-check-conditions node sch-context)
              ;; register answer state
              (push (dag-node-datum node)
                    (rwl-sch-context-answers sch-context))
              ;;
              (when (and (or (= (rwl-state-depth state) 0)
                             *print-every-exec-finding*)
                         (not *rwl-search-no-state-report*))
                (let ((*print-indent* (* 2 (rwl-state-depth state))))
                  (print-next)
                  (format t "** Found [state ~D-~D] " (rwl-state-depth state) (rwl-state-state state))
                  (term-print-with-sort (rwl-state-term state))
                  (print-next)
                  (format t "-- target: ")
                  (term-print (rwl-sch-context-pattern sch-context))
                  (dolist (sub (rwl-state-subst state))
                    (print-subst-if-binding-result state sub sch-context))
                  (print-next)))
              (setf (sch-node-is-solution node) t) ; mark the node as solution
              (incf (rwl-sch-context-sol-found sch-context))
              (setq found? :found)      ; we found at least one solution
              ;; check the # of solutions
              (when (>= (rwl-sch-context-sol-found sch-context)
                        (rwl-sch-context-max-sol sch-context))
                ;; reaches to the # solutions required.
                ;; mesg
                (when (and (= 0 (rwl-state-depth state))
                           (not *rwl-search-no-state-report*))
                  (format t "~%-- found required number of solutions ~D."
                          (rwl-sch-context-max-sol sch-context)))
                (return-from rwl-step-forward-1 (values :max-solutions nil))))))
        )                               ; continue
      )                                 ; end loop
    ;;
    ;; 2. perform the next transitions for each node
    ;;
    (when *chaos-verbose*
      (format t "~%** precompute the next all states......"))
    ;; increment depth
    (incf (rwl-sch-context-cur-depth sch-context))
    ;;
    (let ((next-subs nil))
      (dolist (n (rwl-sch-context-last-siblings sch-context))
        ;; (unless n (break "wow! wow! "))
        (let ((subs (cexec-term-1 n sch-context))
              (nexts nil))
          (dolist (state subs)
            (let ((dag (create-sch-node state)))
              (setf (bdag-parent dag) n)
              (push dag (dag-node-subnodes n))
              (if (rwl-state-loop state)
                  ;; mark `done' if the state is already
                  ;; visited before..
                  (progn
                    (setf (sch-node-done dag) t)
                    (when (rwl-sch-context-if sch-context)
                      (when *cexec-debug*
                        (format t "~%** calling check condition for reporting only."))
                      (rwl-sch-check-conditions dag sch-context))) ; for reporting only
                (push dag nexts))))
          (setq next-subs (nconc next-subs nexts))))
      ;; 
      ;; 3. lastly, set the next states as `last-siblings'
      ;;
      (setf (rwl-sch-context-last-siblings sch-context) next-subs)
      ;;
      (values found? (if next-subs
                         nil
                       :no-more)))))

;;; *********
;;; TOP LEVEL functions
;;; *********
(declaim (inline make-anything-is-ok-term))
(defun make-anything-is-ok-term ()
  (make-variable-term *cosmos* (gensym "Univ")))

(defun rwl-search* (t1 t2 max-result max-depth zero? final?
                    &optional cond
                              pred-pat
                              module
                              bind
                              if)
  (declare (type term t1 t2)
           (type (or null t) zero? final?)
           (optimize (speed 3) (safety 0)))
  (with-in-module (module)
    (unless t2
      (setq t2 (make-anything-is-ok-term)))
    ;; t1 and t2 must be in the same connected component
    (let ((t1-sort (term-sort t1))
          (t2-sort (term-sort t2)))
      (unless (is-in-same-connected-component t1-sort t2-sort *current-sort-order*)
        (with-output-chaos-error ('invalid-sort)
          (format t "Sorts of the source term and the target pattern must be in the same connected component.")
          (format t "~%  Source term : ")
          (term-print-with-sort t1)
          (format t "~&  Target pattern: ")
          (term-print-with-sort t2))))
    (let ((svars (term-variables t1))   ; variables in source
          (pvars (term-variables t2))   ; variables in pattern
          (cvars (if cond               ; variables in suchThat
                     (term-variables cond)
                   nil))
          (predvars (if pred-pat        ; variables in stateEq
                        (term-variables pred-pat)
                      nil))
          (ifvars (if if
                      (term-variables if)
                    nil))
          (allvars nil)
          (.rules-so-far. 0))
      (setq allvars (union svars (union pvars ifvars)))
      ;; check suchThat
      (when cvars
        (unless (subsetp cvars allvars)
          (with-output-chaos-error ('invalid-such-that)
            (format t "`suchThat' introduces new variable(s)."))))
      ;; check variables
      (dolist (v svars)
        (when (memq v pvars)
          (with-output-chaos-error ('subject-var-occus)
            (format t "Variable ")
            (term-print-with-sort v)
            ;; (format t " in subject term occurs in target pattern or coditions..")
            (format t " in subject term occurs in target pattern.")
            (format t "~& subject: ")
            (term-print-with-sort t1)
            (format t "~& pattern: ")
            (term-print-with-sort t2))))
      (dolist (v predvars)
        (when (or (memq v svars)
                  (memq v pvars)
                  (memq v cvars))
          (with-output-chaos-error ('invalid-stateEq)
            (format t "Variable ")
            (term-print-with-sort v)
            (format t " in 'stateEq' occurs in subject term or target pattern or 'suchThat'.."))))
      ;;
      (let ((sch-context (make-rwl-sch-context
                          :module module
                          :term t1
                          :pattern t2
                          :condition cond
                          :zero-trans-allowed zero?
                          :final-check final?
                          :max-sol max-result
                          :max-depth max-depth
                          :state-predicate nil
                          :bind bind
                          :if if
                          :term-hash (alloc-svec term-hash-size)))
            (root nil)
            (res nil)
            (no-more nil)
            (found? nil))
        (flet ((make-state-pred-pat ()
                 (cond (pred-pat
                        (let ((vars (term-variables pred-pat)))
                          (declare (type list vars))
                          (unless (sort= (term-sort pred-pat)
                                         *Bool-sort*)
                            (with-output-chaos-error ('invalid-sort)
                              (format t "state equality must be of a term of sort Bool.")))
                          (unless (= 2 (the fixnum (length vars)))
                            (with-output-chaos-error ('number-of-variables)
                              (format t "state equality pattern must have exactly 2 different variables in it, but ~D given." (length vars))))
                          (unless (sort= (variable-sort (car vars))
                                         (variable-sort (cadr vars)))
                            (with-output-chaos-error ('different-variable-sort)
                              (format t "variables in state equality pattern must be of the same sort.")))
                          (unless (sort<= (term-sort t2) (term-sort (car vars))
                                          *current-sort-order*)
                            (with-output-chaos-error ('invalid-variable-sort)
                              (format t "invalid sort of variable in state equality pattern.")))
                          (cons pred-pat vars)))
                       (t nil))))
          ;;
          ;; initialize search context
          ;;
          (setf (rwl-sch-context-cur-depth sch-context) 0
                (rwl-sch-context-sol-found sch-context) 0
                (rwl-sch-context-trans-so-far sch-context) 0
                root (create-sch-node (make-rwl-state :state 0 :term t1 :depth (1+ .rwl-search-depth.))))
          (setf (rwl-sch-context-root sch-context) root
                (rwl-sch-context-last-siblings sch-context) (list root)
                (rwl-sch-context-answers sch-context) nil)
          ;; state equality predicate
          (setf (rwl-sch-context-state-predicate sch-context) (make-state-pred-pat))
          (let ((.rwl-sch-context. sch-context)
                (.cexec-term-hash. (rwl-sch-context-term-hash sch-context))
                (.rwl-search-depth. (1+ .rwl-search-depth.))
                (.ignore-term-id-limit. t))
            (declare (special .rwl-sch-context. .cexec.term-hash. .ignore-term-id-limit.))
            (push sch-context .rwl-context-stack.)
            ;; the first state is 0
            (set-sch-hashed-term t1 .cexec-term-hash. 0)
            ;;
            ;; do the search
            ;;
            (when *cexec-debug*
              (print sch-context))
            (loop
              (when *chaos-verbose*
                (format t "~%** << level ~D >>" (rwl-sch-context-cur-depth sch-context)))
              (multiple-value-setq (res no-more)
                (rwl-step-forward-1 sch-context))
              (case res
                (:max-transitions (return nil)) ; exit loop
                (:max-solutions
                 (setq found? t)
                 (return nil))          ; exit loop
                (:found
                 (setq found? t))       ; continue..
                (otherwise nil))
              (when no-more
                (when (and (= 0 .rwl-search-depth.)
                           (not *rwl-search-no-state-report*))
                  (format t "~%** No more possible transitions."))
                (return nil))           ; exit if no more ...
              ;; one step deeper
              (when (> (rwl-sch-context-cur-depth sch-context)
                       (rwl-sch-context-max-depth sch-context))
                (unless *rwl-search-no-state-report*
                  (format t "~%-- reached to the specified search depth ~D."
                          (rwl-sch-context-max-depth sch-context)))
                (return-from rwl-search*
                  (if (rwl-sch-context-if sch-context)
                      (if (rwl-sch-context-pr-out? sch-context)
                          :found
                        nil)
                    (if found? :found :max-depth))))) ; end loop
            ;; any solution?
            (cond ((rwl-sch-context-if sch-context)
                   (if (rwl-sch-context-pr-out? sch-context)
                       :found
                     nil))
                  (t (if found? 
                         ;; yes
                         :found
                       ;; no
                       res)))))))))

;;; report-rwl-result
;;;
(defun report-rwl-result (res)
  (case res
    (:max-depth
     ;; (format t "~&-- reached to the max depth.")
     )
    (:no-more
     ;; (format t "~&-- no more solutions.")
     )
    (otherwise
     nil))
  res)

;;; RWL-CONTINUE
;;;
(defun rwl-continue (num-tok)
  (multiple-value-bind (num sym)
      (nat*-to-max-option num-tok)
    (declare (ignore sym))
    (report-rwl-result
     (rwl-continue* num))))

(defun rwl-continue+ (num)
  (report-rwl-result (rwl-continue* num)))

(defun rwl-continue* (num)
  (declare (type fixnum num))
  (unless (and .rwl-sch-context.
               (or (null *current-module*)
                   (eq *current-module*
                       (rwl-sch-context-module .rwl-sch-context.))))
    (with-output-chaos-error ('invalid-context)
      (format t "invalid context...")))
  ;;
  (with-in-module ((rwl-sch-context-module .rwl-sch-context.))
    (setf (rwl-sch-context-max-sol .rwl-sch-context.) num)
    (setf (rwl-sch-context-sol-found .rwl-sch-context.) 0)
    (setf (rwl-sch-context-max-depth .rwl-sch-context.) most-positive-fixnum)
    ;;
    ;; do continue search
    ;;
    (let ((sch-context .rwl-sch-context.)
          (res nil)
          (found? nil))
      (loop
        (setq res (rwl-step-forward-1 sch-context))
        (case res
          ((:max-transitions
            :max-solutions
            :no-more)
           (return nil))                ; exit loop
          (:found
           (setq found? t))
          (otherwise nil))
        ;; one step deeper
        (incf (rwl-sch-context-cur-depth sch-context))) ; end loop
      (if found?
          :found
        res))))

;;; RWL-SEARCH
;;;
(defun rwl-search (&key term
                        pattern
                        (max-result most-positive-fixnum)
                        (max-depth most-positive-fixnum)
                        (zero? nil)
                        (final? nil)
                        (cond nil)
                        (pred nil)
                        (bind nil)
                        ;; the followings are experimental
                        (if nil))
  (let ((module (get-context-module))
        max-r
        max-d)
    (if (integerp max-result)
        (setq max-r max-result)
      (if (term-is-builtin-constant? max-result)
          (setq max-r (term-builtin-value max-result))
        (setq max-r most-positive-fixnum)))
    (if (integerp max-depth)
        (setq max-d max-depth)
      (if (term-is-builtin-constant? max-depth)
          (setq max-d (term-builtin-value max-depth))
        (setq max-d most-positive-fixnum)))
    (when (and if (not (term-is-variable? if)))
      (with-output-chaos-warning ()
        (format t "The `if' part is not a varible of sort BOOL, `if' binding is ignored : ")
        (print-next)
        (term-print if)
        (setq if nil)))
    (when *cexec-normalize*
      (let ((*rewrite-exec-mode* nil)
            (*clean-memo-in-normalize* nil))
        (rewrite* term)))
    ;;
    (when *cexec-debug*
      (format t "~%* CEXEC: ")
      (term-print-with-sort term))
    ;;
    (let ((*clean-memo-in-normalize* nil))
      (report-rwl-result 
       (rwl-search* term pattern max-r max-d zero? final? cond pred module bind if)))))

;;; rwl-check-one-step-reachability : term term -> { t | nil }
;;; working hourse of =>
;;;
(defun rwl-check-one-step-reachability (X Y)
  (declare (type term X Y))
  (let ((*clean-memo-in-normalize* nil)
        (*chaos-quiet* t))
    (report-rwl-result
     (rwl-search* X Y 1 1 t nil nil nil *current-module* nil nil))))

;;; rwl-sch-set-result
;;;
(defun rwl-sch-set-result (raw-res)
  (let ((res nil))
    (if (eq raw-res :found)
        (setq res t)
      (setq res nil))
    (setq $$cexec-term (coerce-to-bool res))))

;;; rwl-cont
;;;
(defun rwl-cont (ast)
  (rwl-continue+ (%continue-num ast)))

;;; for downward compatibility
;;;
(defun nat*-to-max-option (term &optional (infinite most-positive-fixnum))
  (if (term-is-builtin-constant? term)
      (values (term-builtin-value term) "")
    (values infinite (car (method-symbol (term-head term))))))

(defun term-pattern-included-in-cexec (t1 t2 max-depth &optional cond)
  (multiple-value-bind (max sym)
      (nat*-to-max-option max-depth)
    (let ((final? nil)
          (zero? nil))
      (case-equal sym
                  ("!" (setq final? t))
                  ("*" (setq zero? t))
                  (otherwise nil))
      (rwl-search* t1 t2 1 max zero? final? cond nil *current-module*))))

;;; EOF