File: cle_patterns.c

package info (click to toggle)
eprover 2.6%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 21,288 kB
  • sloc: ansic: 331,111; csh: 12,026; python: 10,178; awk: 5,825; makefile: 461; sh: 389
file content (1521 lines) | stat: -rw-r--r-- 40,387 bytes parent folder | download
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
/*-----------------------------------------------------------------------

  File  : cle_patterns.c

  Author: Stephan Schulz

  Contents

  Copyright 1998, 1999, 2018 by the author.
  This code is released under the GNU General Public Licence and
  the GNU Lesser General Public License.
  See the file COPYING in the main E directory for details..
  Run "eprover -h" for contact information.

  Created:  Wed Apr 14 22:58:47 MET DST 1999

  -----------------------------------------------------------------------*/

#include "cle_patterns.h"



/*---------------------------------------------------------------------*/
/*                        Global Variables                             */
/*---------------------------------------------------------------------*/


/*---------------------------------------------------------------------*/
/*                      Forward Declarations                           */
/*---------------------------------------------------------------------*/


/*---------------------------------------------------------------------*/
/*                         Internal Functions                          */
/*---------------------------------------------------------------------*/


/*-----------------------------------------------------------------------
//
// Function: get_new_fun_symbol()
//
//   Return a new norm-id for a given arity.
//
// Global Variables: -
//
// Side Effects    : Changes used_idents;
//
/----------------------------------------------------------------------*/

static FunCode get_new_fun_symbol(PatternSubst_p subst, int arity)
{
   long    base;
   IntOrP* where;

   where = PDArrayElementRef(subst->used_idents, arity);
   where->i_val++;
   base = where->i_val;

   assert(base<=NORM_SYMBOL_LIMIT && "Too many function symbols ???");

   return PatternNormCode(base, arity);
}

/*-----------------------------------------------------------------------
//
// Function: pat_symb_comp_val()
//
//   Return the norm id assigned to f_code, or the alpha-rank if
//   symbol is self-bound.
//
// Global Variables: -
//
// Side Effects    : -
//
/----------------------------------------------------------------------*/

FunCode pat_symb_comp_val(PatternSubst_p subst, FunCode f_code)
{
   assert(f_code);

   if(f_code > 0)
   {
      FunCode res = PDArrayElementInt(subst->fun_subst, f_code);

      if(res == f_code)
      {
         assert(res<=subst->sig->f_count);
         res = SigGetAlphaRank(subst->sig,f_code);
      }
      return res;
   }
   else if(VarFCodeIsAltCode(f_code))
   {
      return f_code;
   }
   return PDArrayElementInt(subst->var_subst, -f_code);
}


/*-----------------------------------------------------------------------
//
// Function: pat_symbol_compare()
//
//   Compare two function symbols as follows:
//
//   Originally:
//
//   If either symbol is unbound but should be bound, return
//   to_uncomparable. Otherwise, compare symbols
//   numerically (if truly bound) or by their alpha-ranks (if bound to
//   themselves). Fresh variables are not expected to be bound.
//
//   However: During pattern generation, an unbound symbol can only be
//   bound to a larger symbol, as new pattern symbols are given out in
//   ascending order -> We can always consider a bound symbol to be
//   smaller than an unbound one! (Note that symbols compared here
//   always have the same arity as well, otherwise the structure-based
//   ordering captures it!
//
// Global Variables: -
//
// Side Effects    : -
//
/----------------------------------------------------------------------*/

static CompareResult pat_symbol_compare(PatternSubst_p subst1, FunCode
                                        f1, PatternSubst_p subst2,
                                        FunCode f2)
{
   if(PatSymbolIsBound(subst1, f1) && PatSymbolIsBound(subst2, f2))
   {
      FunCode cmp = pat_symb_comp_val(subst1, f1) -
         pat_symb_comp_val(subst2, f2);

      return Q_TO_PART(cmp);
   }
   else if(PatSymbolIsBound(subst1, f1))
   {
      return to_lesser;
   }
   else if(PatSymbolIsBound(subst1, f2))
   {
      return to_greater;
   }
   return to_uncomparable;
}


/*-----------------------------------------------------------------------
//
// Function: generate_print_rep()
//
//   Given a norm-id, generate the print-representation into *id.
//
// Global Variables: -
//
// Side Effects    : -
//
/----------------------------------------------------------------------*/

static void generate_print_rep(FunCode f, char *id)
{
   assert(PatIdIsNormId(f));
   assert(id);

   sprintf(id, "f%ld_%ld",
           PatternIdGetArity(f),
           PatternIdGetIdent(f));
}


/*-----------------------------------------------------------------------
//
// Function: pat_term_size_compare()
//
//   Compare two terms with (a variant of) the lexicograpic extension
//   to the ordering induced by the default weights. If two symbols of
//   different arities are encountered, the one with the higher arity
//   is always bigger. This ordering is used as the base for pattern
//   comparison and is independend of actual function symbols. Note
//   that terms with more function symbols are smaller in this
//   ordering! Special case: $true is always larger than any other
//   term!
//
// Global Variables: -
//
// Side Effects    : Memory operations
//
/----------------------------------------------------------------------*/

/* This can now probably be done via TermStructWeightCompare */

static CompareResult pat_term_size_compare(Term_p t1, Term_p t2)
{
   PStack_p      stack;
   CompareResult res   = to_equal;
   long          cmp;
   int           i;

   if((t1->f_code == SIG_TRUE_CODE)&&(t2->f_code == SIG_TRUE_CODE))
   {
      return to_equal;
   }
   if(t1->f_code == SIG_TRUE_CODE)
   {
      return to_greater;
   }
   if(t2->f_code == SIG_TRUE_CODE)
   {
      return to_lesser;
   }

   stack  = PStackAlloc();

   PStackPushP(stack, t1);
   PStackPushP(stack, t2);

   while(!PStackEmpty(stack))
   {
      t2 = PStackPopP(stack);
      t1 = PStackPopP(stack);
      if(t1==t2)
      {
         continue;
      }

      assert(TermStandardWeight(t1) == TermWeight(t1,DEFAULT_VWEIGHT,DEFAULT_FWEIGHT));
      assert(TermStandardWeight(t2) == TermWeight(t2,DEFAULT_VWEIGHT,DEFAULT_FWEIGHT));
      cmp = TermStandardWeight(t1) - TermStandardWeight(t2);

      if(cmp < 0)
      {
         res = to_greater;
         break;
      }
      else if(cmp > 0)
      {
         res = to_lesser;
         break;
      }
      assert(cmp == 0);

      /* Now either t1 and t2 are variables or neither is! */

      cmp = t1->arity - t2->arity;

      if(cmp < 0)
      {
         res = to_greater;
         break;
      }
      else if(cmp > 0)
      {
         res = to_lesser;
         break;
      }
      assert(cmp == 0);
      for(i=0; i<t1->arity; i++)
      {
         PStackPushP(stack, t1->args[i]);
         PStackPushP(stack, t2->args[i]);
      }
   }
   PStackFree(stack);
   assert((res!=to_uncomparable)&&(res!=to_unknown));
   return res;
}

/*-----------------------------------------------------------------------
//
// Function: initialize_lit_list()
//
//   For all unused literals in list mark all literals as potentially
//   minimal in all possible directions.
//
// Global Variables: -
//
// Side Effects    : Changes properties
//
/----------------------------------------------------------------------*/

static void initialize_lit_list(PatternSubst_p subst, Eqn_p list)
{
   Eqn_p handle;
   CompareResult cmpres;

   for(handle = list; handle; handle = handle->next)
   {
      if(!EqnQueryProp(handle, EPIsUsed))
      {
         EqnDelProp(handle, EPLPatMinimal|EPRPatMinimal);
         cmpres = PatternTermCompare(subst, handle->lterm, subst,
                                     handle->rterm);
         switch(cmpres)
         {
         case to_equal: /* Equal stays equal, i.e. we need to consider
                           only one case! FALLTHROUGH */
         case to_lesser:
               EqnSetProp(handle,EPLPatMinimal);
               break;
         case to_greater:
               EqnSetProp(handle,EPRPatMinimal);
               break;
         case to_uncomparable:
               EqnSetProp(handle,EPLPatMinimal|EPRPatMinimal);
               break;
         case to_unknown:
         default:
               assert(false);
               break;
         }
      }
   }
}

/*-----------------------------------------------------------------------
//
// Function: mark_minimal_literals()
//
//   Among all literals in list that do not have EPIsUsed set, mark
//   those literal/direction combinations that are potentially minimal
//   in the semi-complete pattern ordering.
//
// Global Variables: -
//
// Side Effects    : Changes properties in clause.
//
/----------------------------------------------------------------------*/

static void mark_minimal_literals(PatternSubst_p subst, Eqn_p list)
{
   Eqn_p handle, compare;
   CompareResult cmpres;

   initialize_lit_list(subst, list);

   for(handle = list; handle; handle = handle->next)
   {
      if(!EqnIsAnyPropSet(handle, EPLPatMinimal|EPRPatMinimal)||
         EqnQueryProp(handle, EPIsUsed))
      {
         continue;
      }
      for(compare = handle->next; compare; compare = compare->next)
      {
         if(EqnQueryProp(compare, EPIsUsed))
         {
            continue;
         }
         if(EqnQueryProp(handle, EPLPatMinimal))
         {
            if(EqnQueryProp(compare, EPLPatMinimal))
            {
               cmpres = PatternTermPairCompare(subst, handle,
                                               PENormal, subst,
                                               compare, PENormal);
               switch(cmpres)
               {
               case to_equal: /* If two literals are _equal_, this
                                 will not change -> we can arbitrarily
                                 pick exactly one -> FALLTHROUGH */
               case to_lesser:
                     EqnDelProp(compare, EPLPatMinimal);
                     break;
               case to_greater:
                     EqnDelProp(handle, EPLPatMinimal);
                     break;
               default:
                     assert(cmpres!=to_unknown);
                     break;
               }
            }
            if(EqnQueryProp(compare, EPRPatMinimal))
            {
               cmpres = PatternTermPairCompare(subst, handle,
                                               PENormal, subst,
                                               compare, PEReverse);
               switch(cmpres)
               {
               case to_equal: /* If two literals are _equal_, this
                                 will not change -> we can arbitrarily
                                 pick exactly one -> FALLTHROUGH */
               case to_lesser:
                     EqnDelProp(compare, EPRPatMinimal);
                     break;
               case to_greater:
                     EqnDelProp(handle, EPLPatMinimal);
                     break;
               default:
                     assert(cmpres!=to_unknown);
                     break;
               }
            }
         }
         if(EqnQueryProp(handle, EPRPatMinimal))
         {
            if(EqnQueryProp(compare, EPLPatMinimal))
            {
               cmpres = PatternTermPairCompare(subst, handle,
                                               PEReverse, subst,
                                               compare, PENormal);
               switch(cmpres)
               {
               case to_equal: /* If two literals are _equal_, this
                                 will not change -> we can arbitrarily
                                 pick exactly one -> FALLTHROUGH */
               case to_lesser:
                     EqnDelProp(compare, EPLPatMinimal);
                     break;
               case to_greater:
                     EqnDelProp(handle, EPRPatMinimal);
                     break;
               default:
                     assert(cmpres!=to_unknown);
                     break;
               }
            }
            if(EqnQueryProp(compare, EPRPatMinimal))
            {
               cmpres = PatternTermPairCompare(subst, handle,
                                               PEReverse, subst,
                                               compare, PEReverse);
               switch(cmpres)
               {
               case to_equal: /* If two literals are _equal_, this
                                 will not change -> we can arbitrarily
                                 pick exactly one -> FALLTHROUGH */
               case to_lesser:
                     EqnDelProp(compare, EPRPatMinimal);
                     break;
               case to_greater:
                     EqnDelProp(handle, EPRPatMinimal);
                     break;
               default:
                     assert(cmpres!=to_unknown);
                     break;
               }
            }
         }
      }
   }
}

/*-----------------------------------------------------------------------
//
// Function: collect_choices()
//
//   For a list of literals collect all possible choices for the next
//   literal to appear in the pattern for the list. Returns number of
//   possibilities, choices are represented by pairs
//   (literal,direction) on the choice stack.
//
// Global Variables: -
//
// Side Effects    : Changes literal properties
//
/----------------------------------------------------------------------*/

static int collect_choices(PatternSubst_p subst, Eqn_p list, PStack_p
                           choices)
{
   int i = 0;
   Eqn_p handle;

   mark_minimal_literals(subst, list);
   for(handle = list; handle; handle = handle->next)
   {
      if(EqnQueryProp(handle, EPIsUsed))
      {
         continue;
      }
      if(EqnQueryProp(handle, EPLPatMinimal))
      {
         PStackPushP(choices, handle);
         PStackPushInt(choices, PENormal);
         i++;
      }
      if(EqnQueryProp(handle, EPRPatMinimal))
      {
         PStackPushP(choices, handle);
         PStackPushInt(choices, PEReverse);
         i++;
      }
   }
   return i;
}

/*-----------------------------------------------------------------------
//
// Function: complete_state()
//
//   Complete a state in the search. A state is described by
//
//   - A list of literals, some of which may be used up already
//     (marked with EPIsUsed)
//   - A stack which contains exactly the used equations (and
//     determines their order in the pattern)
//   - A partial pattern substitution generated from the used literals
//   - A state stack which organizes the search. It contains 3 entries
//     per picked literal:
//     + The pattern-subst pointer before selecting the literal
//     + A stack of choices
//
//  Return true if successful, false if operation is to expensive.
//
// Global Variables: -
//
// Side Effects    : -
//
/----------------------------------------------------------------------*/

static bool complete_state(PatternSubst_p subst, Eqn_p list,
                           PStack_p order, PStack_p state)
{
   PStack_p choices = PStackAlloc();
   int      choice_nr;
   Eqn_p    picked;
   PatEqnDirection dir;

   choice_nr = collect_choices(subst, list, choices);

   while(choice_nr && (choice_nr <= PATTERN_SEARCH_BRANCHLIMIT))
   {
      assert(PStackGetSP(choices) >= 2);
      dir    = PStackPopInt(choices);
      picked = PStackPopP(choices);

      PStackPushInt(state, PStackGetSP(subst->backtrack));
      PStackPushP(state, choices);
      EqnSetProp(picked, EPIsUsed);
      PatternTermPairCompute(subst, picked, dir);
      PStackPushP(order, picked);
      PStackPushInt(order, dir);

      choices = PStackAlloc();
      choice_nr = collect_choices(subst, list, choices);
   }
   PStackFree(choices);

   return (choice_nr == 0);
}

/*-----------------------------------------------------------------------
//
// Function: lit_list_rep_pattern()
//
//   Generate the representative pattern for a list of
//   equations. Return number of possibilities tried, or 0 if routine
//   terminates because the cost is estimated as to expensive.
//
// Global Variables: -
//
// Side Effects    : Memory management, flips properties.
//
/----------------------------------------------------------------------*/

static long lit_list_rep_pattern(Eqn_p list, PatternSubst_p* subst,
                                 PStack_p *order)
{
   PStack_p        best_order = NULL;
   PatternSubst_p  best_subst = NULL;
   PStack_p        state = PStackAlloc();
   PStack_p        choices;
   Eqn_p           picked;
   PatEqnDirection dir;
   PStackPointer   old_sp;
   long            count = 1;
   bool            affordable;

   EqnListDelProp(list, EPIsUsed);

   affordable = complete_state(*subst, list, *order, state);
   best_subst = PatternSubstCopy(*subst);
   best_order = PStackCopy(*order);

   while((!PStackEmpty(state)) && affordable)
   {
      assert(PStackGetSP(state) >= 2);
      assert(PStackGetSP(*order) >= 2);
      PStackDiscardTop(*order); /* Direction */
      picked = PStackPopP(*order);
      EqnDelProp(picked, EPIsUsed);
      old_sp = PStackBelowTopInt(state);
      PatternSubstBacktrack(*subst, old_sp);
      choices = PStackTopP(state);
      if(!PStackEmpty(choices))
      {
         count++;
         assert(PStackGetSP(choices) >= 2);
         dir    = PStackPopInt(choices);
         picked = PStackPopP(choices);

         EqnSetProp(picked, EPIsUsed);
         PatternTermPairCompute(*subst, picked, dir);
         PStackPushP(*order, picked);
         PStackPushInt(*order, dir);
         affordable = complete_state(*subst, list, *order, state);

         if(affordable)
         {
            if(PatternLitListCompare(*subst, *order,
                                     best_subst, best_order)
               == to_lesser)
            {
               PatternSubstFree(best_subst);
               PStackFree(best_order);
               best_subst = PatternSubstCopy(*subst);
               best_order = PStackCopy(*order);
            }
         }
      }
      else
      {
         PStackFree(choices);
         PStackDiscardTop(state); /* Choices */
         PStackDiscardTop(state); /* Old SP */
      }
   }
   while(!PStackEmpty(state))
   {
      choices = PStackPopP(state);/* Choices */
      PStackFree(choices);
      PStackDiscardTop(state);      /* Old SP */
   }
   PStackFree(state);
   assert(!affordable || PStackEmpty(*order));
   PStackFree(*order);
   PatternSubstFree(*subst);
   *order = best_order;
   *subst = best_subst;

   return affordable?count:0;
}

/*---------------------------------------------------------------------*/
/*                         Exported Functions                          */
/*---------------------------------------------------------------------*/

/*-----------------------------------------------------------------------
//
// Function: PatternSubstAlloc()
//
//   Allocate an empty initialized pattern-substitution cell.
//
// Global Variables: -
//
// Side Effects    : Memory operations
//
/----------------------------------------------------------------------*/

PatternSubst_p PatternSubstAlloc(Sig_p sig)
{
   PatternSubst_p handle = PatternSubstCellAlloc();

   handle->used_idents = PDIntArrayAlloc(DEFAULT_SIGNATURE_SIZE,
                                         DEFAULT_SIGNATURE_SIZE);
   handle->fun_subst   = PDIntArrayAlloc(DEFAULT_SIGNATURE_SIZE,
                                         DEFAULT_SIGNATURE_SIZE);
   handle->used_vars   = NORM_VAR_INIT;
   handle->var_subst   = PDIntArrayAlloc(DEFAULT_VARBANK_SIZE,
                                         DEFAULT_VARBANK_SIZE);
   handle->backtrack   = PStackAlloc();
   handle->sig         = sig;
   return handle;
}

/*-----------------------------------------------------------------------
//
// Function: PatternDefaultSubstAlloc()
//
//   Allocate an empty initialized pattern-substitution cell where all
//   special function symbols are bound to themselves.
//
// Global Variables: -
//
// Side Effects    : Memory operations
//
/----------------------------------------------------------------------*/

PatternSubst_p PatternDefaultSubstAlloc(Sig_p sig)
{
   PatternSubst_p handle = PatternSubstAlloc(sig);
   FunCode i;

   for(i=1; i<=sig->f_count; i++)
   {
      if(SigIsSpecial(sig, i))
      {
         PDArrayAssignInt(handle->fun_subst, i,i);
      }
   }
   return handle;
}


/*-----------------------------------------------------------------------
//
// Function: PatternSubstFree()
//
//   Free the memory taken by a pattern-subst cell.
//
// Global Variables: -
//
// Side Effects    : Memory operations
//
/----------------------------------------------------------------------*/

void PatternSubstFree(PatternSubst_p junk)
{
   PDArrayFree(junk->used_idents);
   PDArrayFree(junk->fun_subst);
   PDArrayFree(junk->var_subst);
   PStackFree(junk->backtrack);

   PatternSubstCellFree(junk);
}



/*-----------------------------------------------------------------------
//
// Function: PatSubstExtend()
//
//   Extend the pattern subst to substitute symbol (if not already
//   done). Return true if the subst has been extended.
//
// Global Variables: -
//
// Side Effects    : Changes used_idents, extends subst
//
/----------------------------------------------------------------------*/

bool PatSubstExtend(PatternSubst_p subst, FunCode symbol, int arity)
{
   long res;
   bool result = false;

   if(symbol > 0)
   {
      res = PDArrayElementInt(subst->fun_subst, symbol);
      if(!res)
      {
         res = get_new_fun_symbol(subst, arity);
         PDArrayAssignInt(subst->fun_subst, symbol, res);
         PStackPushInt(subst->backtrack, symbol);
         result = true;
      }
   }
   else
   {
      assert(symbol < 0);
      if(!VarFCodeIsAltCode(symbol))
      {
         res = PDArrayElementInt(subst->var_subst, -symbol);
         if(!res)
         {
            res = --subst->used_vars;
            PDArrayAssignInt(subst->var_subst, -symbol, res);
            PStackPushInt(subst->backtrack, symbol);
            result = true;
         }
      }
   }
   return result;
}



/*-----------------------------------------------------------------------
//
// Function: PatternSubstCopy()
//
//   Copy a pattern-substitution.
//
// Global Variables: -
//
// Side Effects    : Memory operations
//
/----------------------------------------------------------------------*/

PatternSubst_p PatternSubstCopy(PatternSubst_p subst)
{
   PatternSubst_p handle = PatternSubstCellAlloc();

   handle->used_idents = PDArrayCopy(subst->used_idents);
   handle->fun_subst   = PDArrayCopy(subst->fun_subst);
   handle->used_vars   = subst->used_vars;
   handle->var_subst   = PDArrayCopy(subst->var_subst);
   handle->backtrack   = PStackCopy(subst->backtrack);
   handle->sig         = subst->sig;

   return handle;

}

/*-----------------------------------------------------------------------
//
// Function: PatSymbValue()
//
//   Return the norm id assigned to f_code.
//
// Global Variables:
//
// Side Effects    :
//
/----------------------------------------------------------------------*/

FunCode PatSymbValue(PatternSubst_p subst, FunCode f_code)
{
   assert(f_code);

   if(f_code > 0)
   {
      if(SigIsSpecial(subst->sig, f_code))
      {
         return f_code;
      }
      return PDArrayElementInt(subst->fun_subst, f_code);
   }
   else if(VarFCodeIsAltCode(f_code))
   {
      return f_code;
   }
   return PDArrayElementInt(subst->var_subst, -f_code);
}

/*-----------------------------------------------------------------------
//
// Function: PatSymbolIsBound()
//
//   Return true is f_code is either bound to a symbol or should not
//   be bound at all.
//
// Global Variables: -
//
// Side Effects    : -
//
/----------------------------------------------------------------------*/

bool PatSymbolIsBound(PatternSubst_p subst, FunCode f_code)
{
   return (PatSymbValue(subst, f_code) != 0);
}


/*-----------------------------------------------------------------------
//
// Function: PatternSubstBacktrack()
//
//   Backtrack a pattern-subst to a given state. Return true if the
//   state differs from the current one.
//
// Global Variables: -
//
// Side Effects    : -
//
/----------------------------------------------------------------------*/

bool PatternSubstBacktrack(PatternSubst_p subst, PStackPointer
                           old_state)
{
   bool    res = false;
   FunCode symbol, rep_symbol;

   assert(subst);
   assert(old_state <= PStackGetSP(subst->backtrack));

   while(PStackGetSP(subst->backtrack) > old_state)
   {
      symbol = PStackPopInt(subst->backtrack);

      if(symbol < 0)
      {
         rep_symbol = PDArrayElementInt(subst->var_subst, -symbol);
         assert(subst->used_vars == rep_symbol);
         subst->used_vars++;
         PDArrayAssignInt(subst->var_subst, -symbol, 0);
      }
      else
      {
         int arity, count;
         IntOrP *tmp;

         rep_symbol = PDArrayElementInt(subst->fun_subst, symbol);
         arity = PatternIdGetArity(rep_symbol);
         count = PatternIdGetIdent(rep_symbol);

         tmp = PDArrayElementRef(subst->used_idents, arity);
         UNUSED(count); assert(tmp->i_val == count);
         tmp->i_val--;
         PDArrayAssignInt(subst->fun_subst, symbol, 0);
      }

      res = true;
   }
   return res;
}


/*-----------------------------------------------------------------------
//
// Function: PatternTermCompute()
//
//   Extend subst to make term into a pattern. Return true if a new
//   renaming has been added.
//
// Global Variables:
//
// Side Effects    :
//
/----------------------------------------------------------------------*/

bool PatternTermCompute(PatternSubst_p subst, Term_p term)
{
   int i;
   bool res, tmp;

   assert(term);
   assert(subst);

   res = PatSubstExtend(subst, term->f_code, term->arity);

   for(i=0; i< term->arity; i++)
   {
      assert(!TermIsVar(term));
      assert(term->args[i]);
      tmp = PatternTermCompute(subst, term->args[i]);
      res = res||tmp;
   }
   return res;
}


/*-----------------------------------------------------------------------
//
// Function: PatternTermCompare()
//
//   Compare two term patterns.
//
// Global Variables: -
//
// Side Effects    : Memory operations.
//
/----------------------------------------------------------------------*/

CompareResult PatternTermCompare(PatternSubst_p subst1, Term_p t1,
                                 PatternSubst_p subst2, Term_p t2)
{
   CompareResult res;

   res = pat_term_size_compare(t1, t2);
   assert((res!=to_uncomparable)&&(res!=to_unknown));

   if(res != to_equal)
   {
      return res;
   }
   else
   {
      PStack_p stack = PStackAlloc();
      int i;

      PStackPushP(stack, t1);
      PStackPushP(stack, t2);

      while(!PStackEmpty(stack))
      {
         t2 = PStackPopP(stack);
         t1 = PStackPopP(stack);

         assert(t1->arity == t2->arity);

         res = pat_symbol_compare(subst1, t1->f_code, subst2,
                                  t2->f_code);
         if(res != to_equal)
         {
            break;
         }
         for(i=0; i<t1->arity; i++)
         {
            PStackPushP(stack, t1->args[i]);
            PStackPushP(stack, t2->args[i]);
         }
      }
      PStackFree(stack);
      return res;
   }
}


/*-----------------------------------------------------------------------
//
// Function: PatternTermPairCompute()
//
//   Compute a pattern subst for a given equation.
//
// Global Variables: -
//
// Side Effects    : Changes subst.
//
/----------------------------------------------------------------------*/
bool PatternTermPairCompute(PatternSubst_p subst, Eqn_p eqn,
                            PatEqnDirection direction)
{
   bool res, tmp;

   if(!direction)
   {
      res = PatternTermCompute(subst, eqn->lterm);
      tmp = PatternTermCompute(subst, eqn->rterm);
      res = res || tmp;
   }
   else
   {
      res = PatternTermCompute(subst, eqn->rterm);
      tmp = PatternTermCompute(subst, eqn->lterm);
      res = res || tmp;
   }
   return res;
}


/*-----------------------------------------------------------------------
//
// Function: PatternTermPairCompare()
v//
//   Compare two equation patterns (described by pattern-subst, eqn,
//   direction).
//
// Global Variables:
//
// Side Effects    :
//
/----------------------------------------------------------------------*/

CompareResult PatternTermPairCompare(PatternSubst_p subst1, Eqn_p
                                     eqn1, PatEqnDirection dir1,
                                     PatternSubst_p subst2, Eqn_p
                                     eqn2, PatEqnDirection dir2)
{
   Term_p l1,l2,r1,r2;
   CompareResult res;
   long cmpres;

   cmpres = EqnStandardWeight(eqn2) - EqnStandardWeight(eqn1);

   if(cmpres)
   {
      return Q_TO_PART(cmpres);
   }

   l1 = PatEqnLTerm(eqn1,dir1);
   r1 = PatEqnRTerm(eqn1,dir1);
   l2 = PatEqnLTerm(eqn2,dir2);
   r2 = PatEqnRTerm(eqn2,dir2);

   res = pat_term_size_compare(l1, l2);
   if(res!=to_equal)
   {
      return res;
   }
   res = pat_term_size_compare(r1, r2);
   if(res!=to_equal)
   {
      return res;
   }

   if(EqnIsPositive(eqn1))
   {
      if(EqnIsNegative(eqn2))
      {
         return to_greater;
      }
   }
   else
   {
      if(EqnIsPositive(eqn2))
      {
         return to_lesser;
      }
   }

   res = PatternTermCompare(subst1, l1, subst2, l2);
   if(res != to_equal)
   {
      return res;
   }
   res = PatternTermCompare(subst1, r1, subst2, r2);

   return res;
}


/*-----------------------------------------------------------------------
//
// Function: PatternLitListCompute()
//
//   Compute a pattern-subst for the list (well, stack) of oriented
//   literals.
//
// Global Variables: -
//
// Side Effects    : Changes subst
//
/----------------------------------------------------------------------*/

bool PatternLitListCompute(PatternSubst_p subst, PStack_p listrep)
{
   bool  res = false, tmp;
   Eqn_p eqn;
   PatEqnDirection dir;
   PStackPointer i;

   for(i=0; i<PStackGetSP(listrep); i+=2)
   {
      assert(i+1 < PStackGetSP(listrep));
      eqn = PStackElementP(listrep, i);
      dir = PStackElementInt(listrep, i+1);

      tmp = PatternTermPairCompute(subst, eqn, dir);
      res = res || tmp;
   }
   return res;
}

/*-----------------------------------------------------------------------
//
// Function: PatternLitListCompare()
//
//   Compare two patterns for clauses, each represented by a pattern
//   substitution and a stack of (oriented) literals. This does not
//   correspond exactly to the definition in my thesis, but agrees
//   with it on comparisons of different patterns for the same clause
//   (while being easier and more efficient in the general case, where
//   it does not matter).
//
// Global Variables:
//
// Side Effects    :
//
/----------------------------------------------------------------------*/

CompareResult PatternLitListCompare(PatternSubst_p subst1, PStack_p
                                    listrep1, PatternSubst_p subst2,
                                    PStack_p listrep2)
{
   long cmpres;
   PStackPointer i;
   Eqn_p eqn1, eqn2;
   int dir1, dir2;
   CompareResult res = to_equal;

   cmpres = PStackGetSP(listrep1)-PStackGetSP(listrep2);
   if(cmpres)
   {
      return Q_TO_PART(cmpres);
   }
   for(i=0; i < PStackGetSP(listrep1); i+=2)
   {
      assert(i+1 < PStackGetSP(listrep1));
      eqn1 = PStackElementP(listrep1, i);
      dir1 = PStackElementInt(listrep1, i+1);
      eqn2 = PStackElementP(listrep2, i);
      dir2 = PStackElementInt(listrep2, i+1);

      res = PatternTermPairCompare(subst1, eqn1, dir1, subst2, eqn2,
                                   dir2);
      if(res != to_equal)
      {
         break;
      }
   }
   return res;
}

/*-----------------------------------------------------------------------
//
// Function: PatternClauseCompute()
//
//   Compute the representative pattern for a clause and return it
//   (via the reference variables). Returns number of substitutions
//   tried, or 0 if the internal resource estimator canceled the
//   computation.
//
// Global Variables: -
//
// Side Effects    : Memory operations, may flip some literal flags.
//
/----------------------------------------------------------------------*/

long PatternClauseCompute(Clause_p clause, PatternSubst_p* subst,
                          PStack_p *listrep)
{
   long res;

   res = lit_list_rep_pattern(clause->literals, subst, listrep);

   /* printf("# %d literals, %ld tries\n", ClauseLiteralNumber(clause),
      res);
      if(res > 500)
      {
      printf("# Large clause: ");
      ClausePrint(stdout, clause, true);
      printf("\n");
      } */
   return res;
}


/*-----------------------------------------------------------------------
//
// Function: PatternTermPrint()
//
//   Print the pattern-term to out. Supports only standard E syntax.
//
// Global Variables: -
//
// Side Effects    : Output
//
/----------------------------------------------------------------------*/

void PatternTermPrint(FILE* out, PatternSubst_p subst, Term_p term,
                      Sig_p sig)
{
   FunCode id;
   int  i;
   char new_id[27];

   id = PatSymbValue(subst, term->f_code);
   if(TermIsVar(term))
   {
      if(!id)
      {
         fprintf(out, "X%ld", -term->f_code);
      }
      else
      {
         fprintf(out, "Xn%ld", -(id-NORM_VAR_INIT));
      }
   }
   else
   {
      if(id >= NORM_SYMBOL_LIMIT)
      {
         generate_print_rep(id, new_id);
         fputs(new_id, out);
      }
      else
      {
         fputs(SigFindName(sig, term->f_code), out);
      }
      if(term->arity)
      {
         fprintf(out, "(");
         PatternTermPrint(out, subst, term->args[0], sig);

         for(i=1; i<term->arity; i++)
         {
            fprintf(out, ",");
            PatternTermPrint(out, subst, term->args[i], sig);
         }
         fprintf(out, ")");
      }
   }
}


/*-----------------------------------------------------------------------
//
// Function: PatternEqnPrint()
//
//   Print a pattern equation in the most reasonable form.
//
// Global Variables:
//
// Side Effects    :
//
/----------------------------------------------------------------------*/

void PatternEqnPrint(FILE* out, PatternSubst_p subst, Eqn_p eqn,
                     PatEqnDirection direction)
{
   if(EqnIsEquLit(eqn))
   {
      if(!direction)
      {
         PatternTermPrint(out, subst, eqn->lterm, eqn->bank->sig);
         fputs(EqnIsPositive(eqn)?"=":"!=", out);
         PatternTermPrint(out, subst, eqn->rterm, eqn->bank->sig);
      }
      else
      {
         PatternTermPrint(out, subst, eqn->rterm, eqn->bank->sig);
         fputs(EqnIsPositive(eqn)?"=":"!=", out);
         PatternTermPrint(out, subst, eqn->lterm, eqn->bank->sig);
      }
   }
   else
   {
      if(!EqnIsPositive(eqn))
      {
         fputc('~', out);
      }
      PatternTermPrint(out, subst, eqn->lterm, eqn->bank->sig);
   }
}


/*-----------------------------------------------------------------------
//
// Function: PatternClausePrint()
//
//   Print the clause pattern represented by listrep and
//   subst and print it as a LOP list of literals. This format is
//   primarily for machine use. Regularity and compactness are more
//   important than beauty.
//
// Global Variables: -
//
// Side Effects    : Output
//
/----------------------------------------------------------------------*/

void PatternClausePrint(FILE* out, PatternSubst_p subst, PStack_p
                        listrep)
{
   Eqn_p eqn;
   PatEqnDirection dir;
   PStackPointer i;
   char* prefix = "";

   for(i=0; i<PStackGetSP(listrep); i+=2)
   {
      assert(i+1 < PStackGetSP(listrep));
      eqn = PStackElementP(listrep, i);
      dir = PStackElementInt(listrep, i+1);
      fputs(prefix, out);
      PatternEqnPrint(out, subst, eqn, dir);
      prefix = ";";
   }
   fputs(" <- .", out);
}

/*-----------------------------------------------------------------------
//
// Function: DebugPatternClauseToStack()
//
//   Generate the straightforward stack representation of clause
//   (probably useful only for debugging and testing). The calling
//   function has to return the stack!
//
// Global Variables: -
//
// Side Effects    : Memory operations.
//
/----------------------------------------------------------------------*/

PStack_p DebugPatternClauseToStack(Clause_p clause)
{
   PStack_p res = PStackAlloc();
   Eqn_p    handle;

   for(handle = clause->literals; handle; handle = handle->next)
   {
      PStackPushP(res, handle);
      PStackPushInt(res, PENormal);
   }
   return res;
}


/*-----------------------------------------------------------------------
//
// Function: PatternTranslateSig()
//
//   Create a copy of (uninstantiated) term in new_sig and new_vars,
//   inserting all
//   necessary idents and print-representations of norm-idents into
//   new_sig. Norm-substituted variables are mapped to their unnormed
//   counterparts.
//
// Global Variables: -
//
// Side Effects    : Changes new_sig,  changes
//
/----------------------------------------------------------------------*/

Term_p PatternTranslateSig(Term_p term, PatternSubst_p subst, Sig_p
                           old_sig, Sig_p new_sig, VarBank_p new_vars)
{
   char     new_id[27];
   char*    id;
   PStack_p stack = PStackAlloc();
   Term_p   t, new;
   FunCode  f_code;
   int      i;

   /* Deal with variables...this is messy ;-) */
   PStackPushP(stack, term);
   while(!PStackEmpty(stack))
   {
      t = PStackPopP(stack);
      if(TermIsVar(t))
      {
         f_code = PatSymbValue(subst, t->f_code);
         if(f_code)
         {
            t->binding = VarBankVarAssertAlloc(new_vars, f_code-NORM_VAR_INIT, t->type);
         }
      }
      else
      {
         for(i=0; i<t->arity; i++)
         {
            PStackPushP(stack, t->args[i]);
         }
      }
   }

   new = TermCopy(term, new_vars, DEREF_ONCE);
   /* Reset variables */
   PStackPushP(stack, term);
   while(!PStackEmpty(stack))
   {
      t = PStackPopP(stack);
      if(TermIsVar(t))
      {
         t->binding = NULL;
      }
      else
      {
         for(i=0; i<t->arity; i++)
         {
            PStackPushP(stack, t->args[i]);
         }
      }
   }

   PStackPushP(stack, new);

   while(!PStackEmpty(stack))
   {
      t = PStackPopP(stack);
      if(TermIsVar(t))
      {
         continue;
      }
      f_code = PatSymbValue(subst, t->f_code);
      if(PatIdIsNormId(f_code))
      {
         generate_print_rep(f_code, new_id);
         t->f_code = SigInsertId(new_sig, new_id, t->arity, false);
         assert(t->f_code);
      }
      else
      {
         id = SigFindName(old_sig, t->f_code);
         assert(id);
         t->f_code = SigInsertId(new_sig, id, t->arity, false);
         assert(t->f_code);
      }
      for(i=0; i<t->arity; i++)
      {
         PStackPushP(stack, t->args[i]);
      }
   }
   PStackFree(stack);
   return new;
}

/*-----------------------------------------------------------------------
//
// Function: PatternSubstGetOriginalSymbol()
//
//   Given a symbol f, return the original FunCode. Return 0 if f_code
//   does not match any known symbol.
//
// Global Variables: -
//
// Side Effects    : -
//
/----------------------------------------------------------------------*/

FunCode PatternSubstGetOriginalSymbol(PatternSubst_p subst, FunCode f)
{
   long i;

   if(f > 0)
   {
      for(i=0; i<subst->fun_subst->size; i++)
      {
         if(PDArrayElementInt(subst->fun_subst, i)==f)
         {
            return i;
         }
      }
      return 0;
   }
   else
   {
      if(VarFCodeIsAltCode(f))
      {
         return f;
      }
      else
      {
         for(i=0; i<subst->fun_subst->size; i++)
         {
            if(PDArrayElementInt(subst->var_subst, i)==f)
            {
               return i;
            }
         }
         return 0;
      }
   }
}

/*---------------------------------------------------------------------*/
/*                        End of File                                  */
/*---------------------------------------------------------------------*/