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

#include <ctype.h>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <assert.h>
#include <map>
#include <set>

#include "../lib/crc32.hh"

//#define USE_CONTINUATIONS

namespace
{
    std::string trim(const std::string& s);

    const unsigned ShortLabelLength = 3u;

    struct Operation
    {
        enum { Opcode, ImmedFunc, OpcodeFunc } type;
        std::string result;
    };
    struct Match
    {
        enum { FixedOpcode, Immed, AnyOpcode } type;
        std::string name;         // opcode name such as cInt, or holder name such as x or X
        std::string condition;    // condition that applies when Immed or AnyOpcode

        bool operator==(const Match& b) const
        {
            return type==b.type
                && name==b.name
                && condition==b.condition;
        }

        std::vector<Operation> operations;
        bool has_operations;
        unsigned defined_on_line;
    };
    struct Node
    {
        Match opcode;
        std::vector<Node*> predecessors;
    };

    Node global_head;
    std::set<std::string> PossiblyUnusedLabelList;
    unsigned DefaultLabelCounter;

    std::string trim(const std::string& s)
    {
        size_t rm_begin = 0;
        while(rm_begin < s.size() && s[rm_begin] == ' ') ++rm_begin;
        size_t rm_end = 0;
        while(rm_end < s.size()-rm_begin && s[s.size()-1-rm_end] == ' ') ++rm_end;
        std::string result (s, rm_begin, s.size()-rm_end-rm_begin );
        do {
            std::string::size_type spos = result.find(' ');
            if(spos == result.npos) break;
            result.erase(spos, 1);
        } while(true);
        return result;
    }

    std::string Indent(size_t ntabs, size_t nspaces=0)
    {
        return std::string(ntabs, '\t') + std::string(nspaces, ' ');
    }

    std::string Bexpr(size_t pos)
    {
        if(pos == 0) return "opcode";
        std::ostringstream tmp;
        tmp << "ByteCodePtr[" << -int(pos-1) << "]";
        return tmp.str();
    }

    std::string Iexpr(size_t pos)
    {
        std::ostringstream tmp;
        tmp << "ImmedPtr[" << -int(pos) << "]";
        return tmp.str();
    }

    std::string BexprName(size_t pos)
    {
        if(pos == 0) return "opcode";
        std::ostringstream tmp;
        tmp << "op_" << pos;
        return tmp.str();
    }

    bool HasHandlingFor(const std::string& opcode)
    {
        if(!(opcode[0] == 'c' && isupper(opcode[1])))
            return true;

        if(opcode == "cImmed" || opcode == "cDup") return false;

        for(size_t b=0; b<global_head.predecessors.size(); ++b)
            if(global_head.predecessors[b]->opcode.type == Match::FixedOpcode
            && global_head.predecessors[b]->opcode.name == opcode)
                return true;

        for(size_t b=0; b<global_head.predecessors.size(); ++b)
            if(global_head.predecessors[b]->opcode.type == Match::AnyOpcode)
                return true;
        return false;
    }
    bool HasTailCallFor(const std::string& opcode)
    {
        for(size_t b=0; b<global_head.predecessors.size(); ++b)
            if(global_head.predecessors[b]->opcode.type == Match::FixedOpcode
            && global_head.predecessors[b]->opcode.name == opcode)
                return true;
        return false;
    }

    struct LineSeqs
    {
        void OutChain(std::ostream& out,
                      const std::vector<std::string>& chain,
                      size_t indent)
        {
            std::string codehash, prevlabel;
            for(size_t a=chain.size(); a-- > 0; )
            {
                codehash += chain[a];
                std::string label = GenLabel(codehash);
                Chains::iterator i = code.lower_bound(label);
                if(i != code.end() && i->first == label)
                {
                    std::string got_chain;
                    for(Chains::iterator j = i; j != code.end(); )
                    {
                        got_chain.insert(0, j->second.code);
                        if(j->second.nextlabel.empty()) break;
                        j = code.find(j->second.nextlabel);
                    }
                    /*
                    std::cerr << "expected: <" << codehash << ">\n"
                                 "got:      <" << got_chain << ">\n",
                    */
                    assert(got_chain == codehash);

                    // nothing to do
                    i->second.n_uses += 1;
                    if(!prevlabel.empty())
                        code.find(prevlabel)->second.n_uses -= 1;
                }
                else
                {
                    ChainItem item;
                    item.code         = chain[a];
                    item.nextlabel    = prevlabel;
                    item.n_uses       = 1;
                    code.insert(i, std::make_pair(label, item));
                }
                prevlabel = label;
            }
            if(!prevlabel.empty())
            {
                heads.push_back(prevlabel);
                out << Indent(indent) << "goto " << ChangeLabel(prevlabel) << ";\n";
            }
        }
        void Flush(std::ostream& out)
        {
            std::set<std::string> done;
            std::vector<std::string> remain;

            for(size_t a=0; a<heads.size(); ++a)
            {
                if(done.find(heads[a]) != done.end())
                    continue;

                size_t mini = 0;
                remain.push_back(heads[a]);
                while(!remain.empty())
                {
                    Chains::const_iterator i = code.find(remain.back());
                    remain.pop_back();

                    const ChainItem& item = i->second;
                    done.insert(i->first);

                    if(item.n_uses > mini)
                    {
                        std::string l = ChangeLabel(i->first);
                        out << l << ": ";
                    }
                    else
                        out << std::string(ShortLabelLength+2, ' ');
                    //out << " /*" << item.n_uses << "*/ ";
                    out << item.code;
                    if(!item.nextlabel.empty())
                    {
                        if(done.find(item.nextlabel) != done.end())
                        {
                            std::string l = ChangeLabel(item.nextlabel);
                            out << " goto " << l << ';';
                        }
                        else
                            remain.push_back(item.nextlabel);
                    }
                    else if(item.code.compare(0,5,"goto ") != false)
                        out << " return;";
                    out << "\n";

                    mini = 1;
                }
            }
        }
        void clear()
        {
            heads.clear();
            label_trans.clear();
            code.clear();
        }
    private:
        std::string GenLabel(unsigned crc, unsigned len)
        {
            /* If you get duplicate label errors from the resulting code
             * and the only thing you have done is add more optimization
             * rules, just uncomment one of these characters to enable
             * its use in the label name. If they are all already in use,
             * you will need to increase the ShortLabellength setting by one.
             */
            static const char table[] =
                /*"0123456789"*/
                /*"ABCDEFGHIJKLMNOPQRSTUVWXYZ"*/
                "abcdefghijklmnopq"
                /*"rstuvwxyz_"*/;
            char result[16] = {0};
            int o=15;
            while(true)
            {
                result[--o] = table[crc % (sizeof(table)-1)];
                crc /= (sizeof(table)-1);
                if(crc == 0 && (16-o) > 2) break;
            }
            result[--o] = 'L';
            std::string result2(result+o);
            result2.resize(len,' ');
            return result2;
        }
        std::string GenLabel(const std::string& code)
        {
            return GenLabel(crc32::calc((const unsigned char*)&code[0], code.size()), 20);
        }
        std::string ChangeLabel(const std::string& orig)
        {
            std::map<std::string, unsigned>::iterator
                j = label_trans.lower_bound(orig);
            if(j != label_trans.end() && j->first == orig)
                return GenLabel(j->second, ShortLabelLength);
            size_t lno = label_trans.size();
            label_trans.insert(j, std::make_pair(orig, lno));
            return GenLabel(unsigned(lno), ShortLabelLength);
        }
    private:
        struct ChainItem
        {
            std::string code;
            std::string nextlabel;
            unsigned n_uses;
        };
        typedef std::map<std::string/*label*/, ChainItem> Chains;
        std::vector<std::string> heads;
        std::map<std::string, unsigned> label_trans;
        Chains code;
    } CodeSeq;

    struct OutCode;
    struct OutLine
    {
        OutLine(OutCode& o) : out(o) { }
        template<typename T>
        OutLine& operator<< (const T& b) { buf << b; return *this; }
        ~OutLine();
    private:
        OutCode& out;
        std::ostringstream buf;
    };
    struct OutCode
    {
        OutCode(std::ostream& o, size_t i)
            : out(o),
              indent(i) { }
        ~OutCode()
        {
            for(size_t a=0; a<seq.size(); )
            {
                if((seq[a][0] == '/' && seq[a][1] == '*')
                || (seq[a][0] == 'n' && seq[a][1] == '_')
                || (seq[a][0] == 'r' && seq[a][1] == 'e' && seq[a][2] == 'p')
                || (seq[a][0] == 'o' && seq[a][1] == 'p' && seq[a][2] == '_')
                  )
                {
                    out << Indent(indent) << seq[a] << "\n";
                    seq.erase(seq.begin()+a);
                }
                else ++a;
            }
            #ifdef USE_CONTINUATIONS
            if(!seq.empty() && seq.back().compare(0,9,"goto Tail")==false)
            {
                size_t skip = 0;
                for(size_t a=0; a<seq.size(); ++a)
                {
                    if(seq[a].compare(0,8,"opcode =") == false)
                    {
                        std::string opcode_assign = seq[a];
                        seq.erase(seq.begin()+a);
                        seq.insert(seq.begin(), opcode_assign);
                        skip = 1;
                        break;
                    }
                }
                if(seq.size() > skip+1)
                {
                    //const std::string tail_label = seq.back().substr(5);
                    //const std::string tail_opcode = tail_label.substr(9, tail_label.size()-10);
                    //CodeSeq.AddContinuation(tail_label, tail_opcode);
                    //std::string continuation_line =
                    //    "/""* Will tailcall " + tail_opcode + " *""/";
                    //seq.insert(seq.begin()+skip, continuation_line);
                    seq.back() = "goto PickContinuation;";
                }
            }
            #endif
            CodeSeq.OutChain(out, seq, indent);
            if(seq.empty())
                out << Indent(indent) << "return;\n";
        }
        void Flush()
        {
            for(size_t a=0; a<seq.size(); ++a)
                out << Indent(indent) << seq[a] << "\n";
            seq.clear();
        }
        bool HasOperations() const { return !seq.empty(); }
    private:
        friend struct OutLine;
        void DidLine(const std::string& line) { seq.push_back(line); }
        std::ostream& out;
        std::vector<std::string> seq;
        size_t indent;
    };
    OutLine::~OutLine()
    {
        out.DidLine(buf.str());
    }

    struct Synther
    {
        Synther(OutCode& o, size_t i)
            : Out(o),
              know_bytecode_offset(true),
              know_immed_offset(true),
              indent(i)
        {
        }

        /* Reset is called before an operation that requires
         * that the vector's size() reflects the state shown
         * in the Ptr variable.
         * It is assumed that what follows is an instruction
         * that may reallocate the vector and invalidate pointers.
         */

        void ResetImmed(int offset = 0)
        {
        #if 0
            if(know_immed_offset)
            {
                OutLine(Out)  << "mData->mImmed.resize( " << (1-offset) << " + ImmedPtr - &mData->mImmed[0] );";
            }
            know_immed_offset = false;
        #else
            know_immed_offset = false;
            PopImmedBy(offset);
        #endif
        }

        void ResetByteCode(int offset = 0)
        {
        #if 0
            if(know_bytecode_offset)
            {
                OutLine(Out)  << "mData->mByteCode.resize( " << (1-offset) << " + ByteCodePtr - &mData->mByteCode[0] );";
            }
            know_bytecode_offset = false;
        #else
            know_bytecode_offset = false;
            PopByteCodeBy(offset);
        #endif
        }

        void ResetBoth(int b_offset, int i_offset)
        {
            ResetImmed(i_offset);
            ResetByteCode(b_offset);
        }

        void PopByteCodeBy(int n)
        {
        #if 0
            if(know_bytecode_offset)
                OutLine(Out)  << "ByteCodePtr -= " << n << ";";
            else
                for(; n > 0; --n)
                    OutLine(Out)  << "mData->mByteCode.pop_back();";
        #else
          #if 0
            for(; n > 0; --n)
                OutLine(Out)  << "mData->mByteCode.pop_back();";
          #else
            if(n == 1)
                OutLine(Out)  << "mData->mByteCode.pop_back();";
            else if(n > 0)
            {
                OutLine(Out) << "for(unsigned tmp=" << n << "; tmp-->0; ) mData->mByteCode.pop_back();";
            }
          #endif
            if(know_bytecode_offset)
            {
                //OutLine(Out)  << "if(mData->mByteCode.empty()) ByteCodePtr = 0; else ByteCodePtr -= " << n << ";";
                OutLine(Out)  << "ByteCodePtr -= " << n << ";";
            }
        #endif
        }

        void PopImmedBy(int n)
        {
        #if 0
            if(know_immed_offset)
                OutLine(Out)  << "ImmedPtr -= " << n << ";";
            else
                for(; n > 0; --n)
                    OutLine(Out)  << "mData->mImmed.pop_back();";
        #else
            if(know_immed_offset)
                OutLine(Out)  << "ImmedPtr -= " << n << ";";
         #if 0
            for(; n > 0; --n)
                OutLine(Out)  << "mData->mImmed.pop_back();";
         #else
            if(n == 1)
                OutLine(Out)  << "mData->mImmed.pop_back();";
            else if(n > 0)
            {
                OutLine(Out) << "for(unsigned tmp=" << n << "; tmp-->0; ) mData->mImmed.pop_back();";
            }
         #endif
        #endif
        }

        bool KnowOffsets() const
        {
            return know_bytecode_offset && know_immed_offset;
        }

    private:
        OutCode& Out;
        bool know_bytecode_offset, know_immed_offset;
        size_t indent;
    };

    bool SynthOperations(
        size_t indent, std::ostream& outstream,
        const std::vector<Match>& so_far,
        const Match& src_node,
        size_t b_used,
        size_t i_used)
    {
        std::vector<Operation> operations ( src_node.operations );

        outstream
            << Indent(indent)
            << "FP_TRACE_BYTECODE_OPTIMIZATION(" << src_node.defined_on_line << ',';

        unsigned n_with_lines = 0;
        std::ostringstream trace_with;
        for(size_t a=0; a<so_far.size(); ++a)
        {
            if(so_far[a].type != Match::Immed
            && so_far[a].type != Match::AnyOpcode) continue;
            if(n_with_lines == 0)
                trace_with << ",\n" << Indent(indent+1) << "\"    with ";
            else
                trace_with << "\n" << Indent(indent+1,4) << "<< \", ";
            trace_with << so_far[a].name << " = \" << ";
            if(so_far[a].type == Match::Immed)
                trace_with << so_far[a].name;
            else
                trace_with << "FP_TRACE_OPCODENAME(" << so_far[a].name << ")";
            ++n_with_lines;
        }
        if(n_with_lines > 0)
            outstream << "\n" << Indent(indent+1);

        outstream << '"';
        for(size_t a=so_far.size(); a-- > 0; )
        {
            if(a+1 != so_far.size()) outstream << " ";
            outstream << so_far[a].name;
            if(!so_far[a].condition.empty())
                outstream << "[" << so_far[a].condition << "]";
        }
        if(n_with_lines > 0)
            outstream << "\",\n" << Indent(indent+1) << "\"";
        else
            outstream << "\", \"";
        for(size_t a=0; a<operations.size(); ++a)
        {
            if(a > 0) outstream << ' ';
            switch(operations[a].type)
            {
                case Operation::ImmedFunc:
                    outstream << '[' << operations[a].result << ']';
                    break;
                case Operation::OpcodeFunc:
                    outstream << '{' << operations[a].result << '}';
                    break;
                case Operation::Opcode:
                    outstream << operations[a].result;
            }
        }
        outstream << "\"";
        if(n_with_lines == 0)
            outstream << ", \"\"";
        else if(n_with_lines == 1)
            trace_with << " << \"\\n\"";
        else
            trace_with << "\n" << Indent(indent+1,4) << "<< \"\\n\"";
        outstream << trace_with.str();
        outstream << ");\n";

        if(!operations.empty() && operations[0].result == "DO_POWI")
        {
            outstream
                << Indent(indent) << "if(TryCompilePowi(" << so_far.back().name << "))\n"
                << Indent(indent) << "  return;\n";
            return false;
        }

        OutCode Out(outstream, indent);

        int n_b_exist  = (int)(b_used-1);
        int n_i_exist  = (int)(i_used  );

        int b_offset = n_b_exist;
        int i_offset = n_i_exist;

        Synther offset_synth(Out, indent);

        bool rep_v_used = false;
        bool op_v_used  = false;

        bool changed = false;
        for(size_t a=0; a<operations.size(); ++a)
        {
            std::string opcode = trim(operations[a].result);
            if(opcode == "DO_STACKPLUS1")
            {
                outstream
                    << Indent(indent) << "incStackPtr();\n"
                    << Indent(indent) << "--mStackPtr;\n";
                continue;
            }

            if(operations[a].type == Operation::ImmedFunc)
            {
                //bool requires_var = false;
                //for(size_t a=0; a<opcode.size(); ++a)
                //    if(isalpha(opcode[a]))
                //        requires_var = true;

                if(i_offset > 0)
                {
                    bool i_redundant = false;
                    const Match& m = so_far[i_offset];
                    if(m.type == Match::Immed && opcode == m.name)
                        i_redundant = true;
                    if(i_redundant)
                    {
                        //requires_var = false;
                        OutLine(Out)
                            << "/* " << Iexpr(i_offset-1) << " = " << opcode << "; */"
                            << " // redundant, matches " << so_far[i_offset].name
                            << " @ " << (i_offset);
                    }
                    else
                    {
                        if(rep_v_used || true)
                            OutLine(Out)  << Iexpr(i_offset-1) << " = " << opcode << ";";
                        else
                        {
                            OutLine(Out)  << "rep_v = " << opcode << ";";
                            OutLine(Out)  << Iexpr(i_offset-1) << " = rep_v;";
                            rep_v_used = true;
                        }
                        changed = true;
                    }
                }
                else
                {
                    offset_synth.ResetImmed();
                    if(rep_v_used || true)
                        OutLine(Out)  << "mData->mImmed.push_back(" << opcode << ");";
                    else
                    {
                        OutLine(Out)  << "rep_v = " << opcode << ";";
                        OutLine(Out)  << "mData->mImmed.push_back(rep_v);";
                        rep_v_used = true;
                    }
                    changed = true;
                }
                //if(requires_var) { Out.Flush(); requires_var = false; }
                --i_offset;
                opcode = "cImmed";
            }

            bool redundant = false;
            if(b_offset > 0 && (!changed || !HasHandlingFor(opcode)))
            {
                const Match& m = so_far[b_offset];
                if(opcode == (m.type == Match::Immed ? "cImmed" : m.name))
                {
                    redundant = true;
                }
            }

            bool requires_var = !(opcode[0] == 'c' && isupper(opcode[1]));

            if(!redundant && HasHandlingFor(opcode))
            {
                if(a+1 == operations.size()
                && opcode[0] == 'c' && isupper(opcode[1])
                && HasTailCallFor(opcode))
                {
                    if(b_offset > 0 && i_offset > 0)
                        offset_synth.ResetBoth(b_offset, i_offset);
                    else
                    {
                        if(b_offset > 0) offset_synth.PopByteCodeBy(b_offset);
                        if(i_offset > 0) offset_synth.PopImmedBy(i_offset);
                    }
                    if(so_far[0].type == Match::FixedOpcode
                    && so_far[0].name == operations.back().result)
                    {
                        OutLine(Out)
                            << "/* opcode = " << operations.back().result << "; */"
                            << " // redundant, matches " << so_far[0].name << " @ 0";
                    }
                    else
                    {
                    #if 0
                        OutLine(Out)
                            << "/* opcode = " << operations.back().result << "; */"
                            << " // redundant, not really needed with tailcalls";
                    #else
                        OutLine(Out)  << "opcode = " << operations.back().result << ";";
                    #endif
                    }

                    if(!offset_synth.KnowOffsets())
                        OutLine(Out)  << "FP_ReDefinePointers();";
                    OutLine(Out) << "FP_TRACE_BYTECODE_ADD(" << opcode << ");";
                    OutLine(Out)  << "goto TailCall_" << opcode << ";";
                    PossiblyUnusedLabelList.erase("TailCall_" + opcode);
                    return true;
                }
                else
                {
                    offset_synth.ResetBoth(b_offset>0 ? b_offset : 0,
                                           i_offset>0 ? i_offset : 0);
                    if(op_v_used || true || opcode[0]!='c' || opcode=="cImmed")
                        OutLine(Out)  << "AddFunctionOpcode(" << opcode << ");";
                    else
                    {
                        OutLine(Out)  << "op_v = " << opcode << ";";
                        OutLine(Out)  << "AddFunctionOpcode(op_v);";
                        op_v_used = true;
                    }
                    //if(requires_var) { Out.Flush(); requires_var = false; }
                    i_offset = b_offset = 0;
                    changed = true;
                }
            }
            else
            {
                if(b_offset > 0)
                {
                    if(redundant)
                    {
                        requires_var = false;
                        OutLine(Out)
                            << "/* " << Bexpr(b_offset) << " = " << opcode << "; */"
                            << " // redundant, matches " << so_far[b_offset].name
                            << " @ " << (b_offset);
                    }
                    else
                    {
                        OutLine(Out)  << Bexpr(b_offset) << " = " << opcode << ";";
                        changed = true;
                    }
                }
                else
                {
                    offset_synth.ResetByteCode();
                    if(op_v_used || true || opcode[0]!='c' || opcode=="cImmed")
                        OutLine(Out)  << "mData->mByteCode.push_back(" << opcode << ");";
                    else
                    {
                        OutLine(Out)  << "op_v = " << opcode << ";";
                        OutLine(Out)  << "mData->mByteCode.push_back(op_v);";
                        op_v_used = true;
                    }
                    changed = true;
                }
                if(requires_var) { Out.Flush(); requires_var = false; }
                --b_offset;
            }
        }
        offset_synth.ResetBoth(b_offset,i_offset);

        if(!Out.HasOperations())
            outstream << "return;\n";
        return true;
    }

    std::set<std::string> declared;

    enum { mode_children = 1, mode_operations = 2 };
    bool Generate(
        const Node& head,
        const std::vector<Match>& so_far,
        size_t indent,
        std::ostream& declarations,
        std::ostream& code,
        size_t b_used,
        size_t i_used,
        int mode = mode_children+mode_operations)
    {
        if(!head.predecessors.empty() && (mode & mode_children))
        {
            std::string last_op_name = BexprName(b_used);
            std::string default_label_name;
            /*
            if(last_op_name != "opcode")
                code << Indent(indent) << "const unsigned " << last_op_name << " = " << Bexpr(b_used) << ";\n";
            code << Indent(indent) << "switch(" << last_op_name << ")\n";
            */
        #ifdef USE_CONTINUATIONS
            if(b_used == 0)
            {
                code << Indent(indent-1,2) << "PickContinuation:\n";
            }
        #endif
            bool needs_default_case = false;
            bool needs_immed_case   = false;
            std::set<std::string> other_cases;
            for(size_t b=0; b<head.predecessors.size(); ++b)
            {
                const Node& n = *head.predecessors[b];
                if(n.opcode.type == Match::AnyOpcode)
                    needs_default_case = true;
                else if(n.opcode.type == Match::Immed)
                    needs_immed_case = true;
                else
                    other_cases.insert(n.opcode.name);
            }
            bool needs_switchcase =
                (needs_immed_case+needs_default_case+other_cases.size()) > 1;

            if(needs_switchcase)
            {
                code << Indent(indent) << "switch(" << Bexpr(b_used) << ")\n";
                code << Indent(indent) << "{\n";
            }

            if(!other_cases.empty())
            {
                unsigned other_indent = needs_switchcase ? 1 : 1;

                for(std::set<std::string>::const_iterator
                    i = other_cases.begin();
                    i != other_cases.end();
                    ++i)
                {
                    const std::string& op = *i;

                #ifndef USE_CONTINUATIONS
                    if(b_used == 0)
                    {
                        code << Indent(indent) << "TailCall_" << op << ":\n";
                        PossiblyUnusedLabelList.insert("TailCall_" + op);

                        /* If ByteCodePtr is null, just add the opcode. */
                        code << Indent(indent) << "if(!ByteCodePtr)\n";
                        code << Indent(indent) << "{\n";
                        { OutCode Out(code, indent+other_indent);
                          Synther(Out, indent+other_indent).ResetBoth(0,0);
                          OutLine(Out) << "mData->mByteCode.push_back(opcode);";
                        }
                        code << Indent(indent) << "}\n";
                    }
                #endif
                    if(needs_switchcase)
                    {
                        code << Indent(indent) << "case " << op << ":\n";
                    }
                    else
                    {
                        code << Indent(indent) << "if(" << Bexpr(b_used) << " == " << op << ")\n"
                             << Indent(indent) << "{\n";
                    }

                    bool returned = false;

                    for(int round=0; round<4; ++round)
                        for(size_t a=0; a<head.predecessors.size(); ++a)
                        {
                            const Node& n = *head.predecessors[a];
                            if(round < 2  && n.opcode.has_operations) continue;
                            if(round >= 2 && !n.opcode.has_operations) continue;
                            if((round & 1) != !!n.opcode.condition.empty()) continue;

                            if(n.opcode.type == Match::FixedOpcode
                            && n.opcode.name == op)
                            {
                                //code << Indent(indent) << "  {\n";
                                std::vector<Match> ref(so_far);
                                ref.push_back(n.opcode);

                                if(n.opcode.condition.empty())
                                {
                                    returned |=
                                        Generate(n, ref, indent+other_indent, declarations,code, b_used+1, i_used, mode_children|(round>=2?mode_operations:0));
                                }
                                else
                                {
                                    code << Indent(indent+other_indent) << "if(" << n.opcode.condition << ")\n";
                                    code << Indent(indent+other_indent) << "{\n";
                                    Generate(n, ref, indent+other_indent+1, declarations,code, b_used+1, i_used, mode_children|(round>=2?mode_operations:0));
                                    code << Indent(indent+other_indent) << "}\n";
                                }
                            }
                        }
                    if(!returned)
                    {
                        if(needs_default_case)
                        {
                            if(default_label_name.empty())
                            {
                                std::ostringstream tmp;
                                tmp << "Default" << DefaultLabelCounter++;
                                default_label_name = tmp.str();
                            }
                            code << Indent(indent+other_indent) << "goto " << default_label_name << ";\n";
                        }
                        else if(needs_switchcase)
                        {
                            code << Indent(indent+other_indent) << "break;\n";
                        }
                    }
                    if(!needs_switchcase)
                        code << Indent(indent) << "}\n";
                }
            }

            std::set<std::string> immed_labels;
            bool immed_returned = false;
            /*
              Round 0:  no-code, has condition,  mode_children
              Round 1:  no-code, no condition,   mode_children
              Round 2:  code, has condition,     mode_children | mode_operations
              Round 3:  code, no condition,      mode_children | mode_operations
            */
            if(needs_immed_case)
            {
                if(needs_switchcase)
                {
                    code << Indent(indent) << "case cImmed:\n";
                }
                else
                {
                    code << Indent(indent) << "if(" << Bexpr(b_used) << " == cImmed)\n"
                         << Indent(indent) << "{\n";
                }
                unsigned imm_indent = needs_switchcase ? 1 : 1;

                for(int round=0; round<4; ++round)
                    for(size_t a=0; a<head.predecessors.size(); ++a)
                    {
                        const Node& n = *head.predecessors[a];
                        if(n.opcode.type == Match::Immed)
                        {
                            if(round < 2  && n.opcode.has_operations) continue;
                            if(round >= 2 && !n.opcode.has_operations) continue;
                            if((round & 1) != !!n.opcode.condition.empty()) continue;

                            //code << Indent(indent) << "  /* round " << round << " a = " << a << " */\n";
                            std::set<std::string>::iterator i = immed_labels.lower_bound(n.opcode.name);
                            if(i == immed_labels.end() || *i != n.opcode.name)
                            {
                                if(declared.find(n.opcode.name) == declared.end())
                                {
                                    declared.insert(n.opcode.name);
                                    declarations << Indent(1) << "Value_t " << n.opcode.name << ";\n";
                                }

                                code << Indent(indent+imm_indent) << n.opcode.name << " = " << Iexpr(i_used) << ";\n";
                                immed_labels.insert(i, n.opcode.name);
                            }
                            std::vector<Match> ref(so_far);
                            ref.push_back(n.opcode);
                            if(n.opcode.condition.empty())
                                immed_returned =
                                    Generate(n, ref, indent+imm_indent, declarations,code, b_used+1, i_used+1, mode_children|(round>=2?mode_operations:0));
                            else
                            {
                                code << Indent(indent+imm_indent) << "if(" << n.opcode.condition << ")\n";
                                code << Indent(indent+imm_indent) << "{\n";
                                Generate(n, ref, indent+imm_indent+1, declarations,code, b_used+1, i_used+1, mode_children|(round>=2?mode_operations:0));
                                code << Indent(indent+imm_indent) << "}\n";
                            }
                        }
                    }

                if(needs_switchcase)
                {
                    if(!immed_returned)
                        code << Indent(indent+imm_indent) << "break;\n";
                }
                else
                {
                    code << Indent(indent) << "}\n";
                }
            }

            std::set<std::string> opcode_labels;

            if(needs_default_case)
            {
                if(needs_switchcase)
                {
                    code << Indent(indent) << "default:";
                    if(!default_label_name.empty())
                        code << " " << default_label_name << ":;";
                    code << "\n";
                }
                unsigned default_indent = needs_switchcase ? 1 : 0;

                for(int round=0; round<4; ++round)
                    for(size_t a=0; a<head.predecessors.size(); ++a)
                    {
                        const Node& n = *head.predecessors[a];
                        if(n.opcode.type == Match::AnyOpcode)
                        {
                            if(round < 2  && n.opcode.has_operations) continue;
                            if(round >= 2 && !n.opcode.has_operations) continue;
                            if((round & 1) != !!n.opcode.condition.empty()) continue;
                            //code << Indent(indent) << "  /* round " << round << " a = " << a << " */\n";
                            std::set<std::string>::iterator i = opcode_labels.lower_bound(n.opcode.name);
                            if(i == opcode_labels.end() || *i != n.opcode.name)
                            {
                                if(declared.find(n.opcode.name) == declared.end())
                                {
                                    declared.insert(n.opcode.name);
                                    declarations << Indent(1) << "unsigned " << n.opcode.name << ";\n";
                                }
                                code << Indent(indent+default_indent) << n.opcode.name << " = " << Bexpr(b_used) << ";\n";
                                opcode_labels.insert(i, n.opcode.name);
                            }
                            std::vector<Match> ref(so_far);
                            ref.push_back(n.opcode);
                            if(n.opcode.condition.empty())
                                Generate(n, ref, indent+default_indent, declarations,code, b_used+1, i_used, mode_children|(round>=2?mode_operations:0));
                            else
                            {
                                code << Indent(indent+default_indent) << "if(" << n.opcode.condition << ")\n";
                                code << Indent(indent+default_indent) << "{\n";
                                Generate(n, ref, indent+default_indent+1, declarations,code, b_used+1, i_used, mode_children|(round>=2?mode_operations:0));
                                code << Indent(indent+default_indent) << "}\n";
                            }
                        }
                    }
            }

            if(needs_switchcase)
            {
                code << Indent(indent) << "}\n";
            }
        }
        if(head.opcode.has_operations && (mode & mode_operations))
        {
            /*if(!head.predecessors.empty())
                std::cout << Indent(indent) << "/""* NOTE: POSSIBLY AMBIGIOUS *""/\n";*/
            if(SynthOperations(indent,code, so_far, head.opcode, b_used, i_used))
            {
                //out << Indent(indent) << "return;\n";
                // ^ now redundant, as it is done by SynthOperations()
                return true;
            }
        }
        return false;
    }

    void Generate(std::ostream& out)
    {
        std::ostringstream code;
        std::ostream& declarations = out;
        Generate(global_head, std::vector<Match>(), 1, declarations,code, 0,0);
        out << code.str();

        { OutCode Out(out, 1);
          Synther(Out, 1).ResetBoth(0,0);
          OutLine(Out) << "mData->mByteCode.push_back(opcode);";
        }
        CodeSeq.Flush(out);

        out << "return;\n";
        out << "// This list of dummy gotos is here to inhibit\n"
               "// compiler warnings on unused labels\n";
        unsigned a=0;
        for(std::set<std::string>::const_iterator
            i = PossiblyUnusedLabelList.begin();
            i != PossiblyUnusedLabelList.end();
            ++i)
        {
            out << "goto " << *i << ";";
            if(a+1 == PossiblyUnusedLabelList.size()
            || a%3 == 2) out << "\n";
            ++a;
        }
    }

    bool isnamech(char c)
    {
        return c=='_' || (c>='a' && c<='z') || (c>='A' && c<='Z');
    }

    void VerifyExpressions(
        const std::set<std::string>& expressions,
        const std::set<std::string>& identifiers,
        unsigned lineno)
    {
        for(std::set<std::string>::const_iterator
            i = expressions.begin();
            i != expressions.end();
            ++i)
        {
            const std::string& e = *i;
            for(size_t a=0; a<e.size(); ++a)
            {
                if( isnamech(e[a])
                && !isnamech(e[a+1])
                && (a==0 || (!isnamech(e[a-1])
                          && !std::isdigit(e[a-1]))
                   ))
                {
                    std::string id(e, a, 1);
                    if(identifiers.find(id) == identifiers.end())
                    {
                        std::cerr
                            << "WARNING: Identifier '" << id
                            << "' used on line " << lineno
                            << " is undefined\n";
                    }
                }
            }
        }
    }

    template<typename T>
    bool SplitConditionString(const std::string& s, T& set, T& unset)
    {
        size_t a=0, b=s.size();
        bool glue_necessary = false;
        while(a < b)
        {
            if(s[a] == ' ') { ++a; continue; }
            if(s[a] == '(' || s[a] == ')') return false; // Cannot evaluate
            bool positive = true;
            if(glue_necessary)
            {
                if(s[a] != '&' || s[a+1] != '&') return false;
                a += 2;
                if(a >= b) return false;
            }
            while(a < b && s[a] == ' ') ++a;
            if(s[a] == '!') { ++a; positive = false; if(a >= b) return false; }
            while(a < b && s[a] == ' ') ++a;
            if(a >= b) return false;
            if((s[a] >= 'A' && s[a] <= 'Z')
            || (s[a] >= 'a' && s[a] <= 'z')
            || s[a]=='_')
            {
                size_t begin = a;
                while(++a < b && ((s[a] >= 'A' && s[a] <= 'Z')
                               || (s[a] >= 'a' && s[a] <= 'z')
                               || (s[a] >= '0' && s[a] <= '9')
                               || s[a]=='_'))
                    { }
                (positive ? set : unset).insert( s.substr(begin, a-begin) );
                glue_necessary = true;
                continue;
            }
            else
                break;
        }
        return true;
    }

    struct ParsingMode
    {
        std::set<std::string> different_preconditions;
        bool collect_preconditions;
        std::set<std::string> allowed_preconditions;
    };
    void Parse(ParsingMode& mode)
    {
        unsigned lineno = 0;
        while(true)
        {
            char Buf[2048];
            if(!std::fgets(Buf, sizeof(Buf), stdin)) break;
            ++lineno;
            char* bufptr = Buf;
            while(*bufptr == ' ' || *bufptr == '\t') ++bufptr;
            if(*bufptr == '#' || *bufptr == '\r' || *bufptr == '\n') continue;

            std::string Precondition;

            if(*bufptr == 'I' && bufptr[1] == 'F' && bufptr[2] == '(')
            {
                bufptr += 3;
                size_t balance = 0;
                while(*bufptr != ')' || balance != 0)
                {
                    if(*bufptr == '\r' || *bufptr == '\n') break;
                    if(*bufptr == '(') ++balance;
                    if(*bufptr == ')') --balance;
                    Precondition += *bufptr++;
                }
                if(*bufptr == ')') ++bufptr;
                while(*bufptr == ' ' || *bufptr == '\t') ++bufptr;
            }

            if(mode.collect_preconditions)
            {
                std::set<std::string> en, dis;
                if(SplitConditionString(Precondition, en, dis))
                {
                    mode.different_preconditions.insert(en.begin(), en.end());
                    mode.different_preconditions.insert(dis.begin(), dis.end());
                }
                else
                {
                    while(!Precondition.empty()
                        && Precondition[0] == '!') Precondition.erase(Precondition.begin());
                    if(!Precondition.empty())
                        mode.different_preconditions.insert(Precondition);
                }
                continue;
            }

            if(!Precondition.empty())
            {
                std::set<std::string> en, dis;
                /*fprintf(stderr, "Rule %u, Condition %s, allowed:",
                    lineno, Precondition.c_str());
                for(std::set<std::string>::const_iterator
                    i = mode.allowed_preconditions.begin();
                    i != mode.allowed_preconditions.end();
                    ++i)
                    fprintf(stderr, " %s", i->c_str());*/

                if(SplitConditionString(Precondition, en, dis))
                {
                    bool ok = true;
                    for(std::set<std::string>::const_iterator
                        i = en.begin(); i != en.end(); ++i)
                    {
                        /*fprintf(stderr, "[en:%s]", i->c_str());*/
                        if(mode.allowed_preconditions.find(*i)
                        == mode.allowed_preconditions.end())
                            { ok = false; break; }
                    }
                    for(std::set<std::string>::const_iterator
                        i = dis.begin(); i != dis.end(); ++i)
                    {
                        /*fprintf(stderr, "[dis:%s]", i->c_str());*/
                        if(mode.allowed_preconditions.find(*i)
                        != mode.allowed_preconditions.end())
                            { ok = false; break; }
                    }
                    /*fprintf(stderr, " - decision: %s\n", ok?"OK":" Not ok");
                    fflush(stderr);*/
                    if(!ok) continue;
                }
                else
                {
                    std::string cond = Precondition;
                    bool inverse = false;
                    while(cond[0] == '!')
                        { inverse = !inverse; cond.erase(cond.begin()); }
                    if((mode.allowed_preconditions.find(cond)
                     == mode.allowed_preconditions.end()) != inverse)
                    {
                        continue;
                    }
                }
            }

            std::set<std::string> identifiers_defined_here;
            std::set<std::string> expressions_used_here;

            std::vector<Match> sequence;
            while(true)
            {
                Match m;
                m.has_operations = false;
                while(*bufptr == ' ' || *bufptr == '\t') ++bufptr;
                if(*bufptr == '-' && bufptr[1] == '>') break;
                while(isalnum(*bufptr)) m.name += *bufptr++;
                m.name = trim(m.name);
                while(*bufptr == ' ' || *bufptr == '\t') ++bufptr;
                if(*bufptr == '#') break;
                if(*bufptr == '[')
                {
                    size_t balance = 0; ++bufptr;
                    while(*bufptr != ']' || balance != 0)
                    {
                        if(*bufptr == '\r' || *bufptr == '\n') break;
                        if(*bufptr == '[') ++balance;
                        if(*bufptr == ']') --balance;
                        m.condition += *bufptr++;
                    }
                    if(*bufptr == ']') ++bufptr;
                    m.condition = trim(m.condition);
                    expressions_used_here.insert(m.condition);
                }
                if(m.name[0] == 'c' && m.name.size() > 1)
                    m.type = Match::FixedOpcode;
                else if(isupper(m.name[0]))
                {
                    m.type = Match::AnyOpcode;
                    identifiers_defined_here.insert(m.name);
                }
                else
                {
                    m.type = Match::Immed;
                    identifiers_defined_here.insert(m.name);
                }

                sequence.push_back(m);
            }

            Node* head = &global_head;
            for(size_t b=sequence.size(); b-->0; )
            {
                const Match& m = sequence[b];
                bool dup = false;
                for(size_t a=0; a< head->predecessors.size(); ++a)
                {
                    if(m == head->predecessors[a]->opcode)
                    {
                        head = head->predecessors[a];
                        dup = true;
                        break;
                    }
                }
                if(!dup)
                {
                    Node* newhead = new Node;
                    newhead->opcode = m;
                    head->predecessors.push_back(newhead);
                    head = newhead;
                }
            }

            if(*bufptr == '-' && bufptr[1] == '>')
            {
                if(head->opcode.has_operations)
                {
                    std::cerr << "WARNING: Duplicate definition on line " << lineno
                              << ", previously defined on line " << head->opcode.defined_on_line
                              << std::endl;
                }
                head->opcode.has_operations = true;
                head->opcode.defined_on_line = lineno;
                bufptr += 2;

                while(true)
                {
                    while(*bufptr == ' ' || *bufptr == '\t') ++bufptr;
                    if(*bufptr == '#' || *bufptr == '\r' || *bufptr == '\n') break;
                    Operation op;
                    if(*bufptr == '[')
                    {
                        size_t balance = 0; ++bufptr;
                        while(*bufptr != ']' || balance != 0)
                        {
                            if(*bufptr == '\r' || *bufptr == '\n') break;
                            if(*bufptr == '[') ++balance;
                            if(*bufptr == ']') --balance;
                            op.result += *bufptr++;
                        }
                        if(*bufptr == ']') ++bufptr;
                        op.type = Operation::ImmedFunc;
                        expressions_used_here.insert(op.result);
                    }
                    else if(*bufptr == '{')
                    {
                        size_t balance = 0; ++bufptr;
                        while(*bufptr != '}' || balance != 0)
                        {
                            if(*bufptr == '\r' || *bufptr == '\n') break;
                            if(*bufptr == '{') ++balance;
                            if(*bufptr == '}') --balance;
                            op.result += *bufptr++;
                        }
                        if(*bufptr == '}') ++bufptr;
                        op.type = Operation::OpcodeFunc;
                        expressions_used_here.insert(op.result);
                    }
                    else
                    {
                        while(isalnum(*bufptr))
                            op.result += *bufptr++;
                        op.type = Operation::Opcode;
                    }
                    head->opcode.operations.push_back(op);
                }
            }

            VerifyExpressions(expressions_used_here,
                              identifiers_defined_here,
                              lineno);
        }
    }

    std::string GetPreconditionMaskName(
        const std::vector<std::string>& cond,
        size_t bitmask)
    {
        std::set<std::string> enabled;
        std::set<std::string> disabled;

        for(size_t b=0; b<cond.size(); ++b)
        {
            if(bitmask & (1 << b))
            {
                std::string c = cond[b];
                /*std::set<std::string> e, d;
                if(!SplitConditionString(c, e, d))*/
                    enabled.insert(c);
                /*else
                {
                    enabled.insert(e.begin(), e.end());
                    disabled.insert(d.begin(), d.end());
                }*/
            }
            else
            {
                disabled.insert(cond[b]);
                // No splitting of conditions here,
                // because !(a && b) yields !a || !b, not !a && !b
            }
        }

        std::string result;
        bool first=true;
        for(std::set<std::string>::const_iterator
            i = enabled.begin(); i != enabled.end(); ++i)
        {
            if(disabled.find(*i) != disabled.end())
                return std::string(); // conflicting conditions
            if(first) first=false; else result += " && ";
            result += "(" + *i + ")";
        }
        for(std::set<std::string>::const_iterator
            i = disabled.begin(); i != disabled.end(); ++i)
        {
            if(first) first=false; else result += " && ";
            result += "!(" + *i + ")";
        }
        return result;
    }
}

int main()
{
    ParsingMode mode;
    mode.collect_preconditions = true;
    Parse(mode);

    std::vector<std::string> different_preconditions(
        mode.different_preconditions.begin(),
        mode.different_preconditions.end() );

    size_t n_different_parsers = 1 << different_preconditions.size();

    std::ostream& out = std::cout;

    out <<
    //  "template<typename Value_t>\n"
    //  "inline void FunctionParserBase<Value_t>::AddFunctionOpcode(unsigned opcode)\n"
    //  "{\n"
        "  unsigned* ByteCodePtr;\n"
        "  Value_t*   ImmedPtr;\n"
        //"  unsigned n_b, n_i, op_v;\n"
        //"  Value_t  rep_v;\n"
        "\n"
        "  #define FP_ReDefinePointers() \\\n"
        "    ByteCodePtr = !mData->mByteCode.empty() ? &mData->mByteCode[0] + mData->mByteCode.size() - 1 : 0; \\\n"
        "    ImmedPtr    = !mData->mImmed.empty()    ? &mData->mImmed[0]    + mData->mImmed.size()    - 1 : 0;\n"
        "  FP_ReDefinePointers();\n";

    out << "  FP_TRACE_BYTECODE_ADD(opcode);\n";

    for(size_t n=0; n<n_different_parsers; ++n)
    {
        mode.collect_preconditions = false;
        mode.allowed_preconditions.clear();
        for(size_t b=0; b<different_preconditions.size(); ++b)
        {
            if(n & (1 << b))
                mode.allowed_preconditions.insert(different_preconditions[b]);
        }
        if(std::fseek(stdin, 0, SEEK_SET) < 0)
        {
            std::perror("fseek");
            return -1;
        }

        global_head = Node();
        PossiblyUnusedLabelList.clear();
        DefaultLabelCounter=0;
        CodeSeq.clear();
        declared.clear();

        Parse(mode);

        out << "\n";

        if(n_different_parsers == 1)
            Generate(out);
        else
        {
            std::string mask = GetPreconditionMaskName(different_preconditions, n);
            if(!mask.empty())
            {
                out << "#if(" << mask << ")\n" << std::flush;
                Generate(out);
                out << "#endif\n";
            }
        }
    }

    out <<
        "\n"
        "#undef FP_ReDefinePointers\n"
    //  "}\n"
        "#undef FP_TRACE_BYTECODE_OPTIMIZATION\n"
        "#undef FP_TRACE_OPCODENAME\n";

    return 0;
}