File: QueryBranchOp.cs

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

    abstract class JumpOpcode : Opcode
    {
        Opcode jump;

        internal JumpOpcode(OpcodeID id, Opcode jump)
            : base(id)
        {
            this.Jump = jump;
            this.flags |= OpcodeFlags.Jump;
        }

        internal Opcode Jump
        {
            get
            {
                return this.jump;
            }
            set
            {
                Fx.Assert(value.ID == OpcodeID.BlockEnd, "");
                this.AddJump((BlockEndOpcode)value);
            }
        }

        internal void AddJump(BlockEndOpcode jumpTo)
        {
            bool conditional = this.IsReachableFromConditional();
            if (conditional)
            {
                this.prev.DelinkFromConditional(this);
            }

            if (null == this.jump)
            {
                this.jump = jumpTo;
            }
            else
            {
                BranchOpcode jumpBranch;
                if (this.jump.ID == OpcodeID.Branch)
                {
                    // already a branch
                    jumpBranch = (BranchOpcode)this.jump;
                }
                else
                {
                    BlockEndOpcode currentJump = (BlockEndOpcode)this.jump;
                    jumpBranch = new BranchOpcode();
                    jumpBranch.Branches.Add(currentJump);
                    this.jump = jumpBranch;
                }
                jumpBranch.Branches.Add(jumpTo);
            }
            jumpTo.LinkJump(this);

            if (conditional && null != this.jump)
            {
                this.prev.LinkToConditional(this);
            }
        }

        internal override void Remove()
        {
            if (null == this.jump)
            {
                base.Remove();
            }
        }

        internal void RemoveJump(BlockEndOpcode jumpTo)
        {
            Fx.Assert(null != this.jump, "");

            bool conditional = this.IsReachableFromConditional();
            if (conditional)
            {
                this.prev.DelinkFromConditional(this);
            }

            if (this.jump.ID == OpcodeID.Branch)
            {
                BranchOpcode jumpBranch = (BranchOpcode)this.jump;
                jumpTo.DeLinkJump(this);
                jumpBranch.RemoveChild(jumpTo);
                if (0 == jumpBranch.Branches.Count)
                {
                    this.jump = null;
                }
            }
            else
            {
                Fx.Assert(object.ReferenceEquals(jumpTo, this.jump), "");
                jumpTo.DeLinkJump(this);
                this.jump = null;
            }

            if (conditional && null != this.jump)
            {
                this.prev.LinkToConditional(this);
            }
        }

        internal override void Trim()
        {
            if (this.jump.ID == OpcodeID.Branch)
            {
                this.jump.Trim();
            }
        }

    }

    class JumpIfOpcode : JumpOpcode
    {
        protected bool test;

        internal JumpIfOpcode(Opcode jump, bool test)
            : this(OpcodeID.JumpIfNot, jump, test)
        {
        }

        protected JumpIfOpcode(OpcodeID id, Opcode jump, bool test)
            : base(id, jump)
        {
            this.test = test;
        }

        internal bool Test
        {
            get
            {
                return this.test;
            }
        }

        internal override bool Equals(Opcode op)
        {
            if (base.Equals(op))
            {
                return (this.test == ((JumpIfOpcode)op).test);
            }

            return false;
        }

        internal override Opcode Eval(ProcessingContext context)
        {
            Fx.Assert(null != context, "");

            StackFrame arg = context.TopArg;
            for (int i = arg.basePtr; i <= arg.endPtr; ++i)
            {
                Fx.Assert(context.Values[i].IsType(ValueDataType.Boolean), "");
                if (this.test == context.Values[i].Boolean)
                {
                    // At least one result satisfies the test. Don't branch
                    return this.next;
                }
            }

            // Jump, since no result is satisfactory..
            return this.Jump;
        }

#if DEBUG_FILTER
        public override string ToString()
        {
            return string.Format("{0} {1}", base.ToString(), this.test);
        }
#endif
    }

    class ApplyBooleanOpcode : JumpIfOpcode
    {
        internal ApplyBooleanOpcode(Opcode jump, bool test)
            : this(OpcodeID.ApplyBoolean, jump, test)
        {
        }

        protected ApplyBooleanOpcode(OpcodeID id, Opcode jump, bool test)
            : base(id, jump, test)
        {
        }

        internal override Opcode Eval(ProcessingContext context)
        {
            int matchCount = this.UpdateResultMask(context);
            context.PopFrame();
            if (0 == matchCount)
            {
                return this.Jump;
            }

            return this.next;
        }

        protected int UpdateResultMask(ProcessingContext context)
        {
            StackFrame results = context.TopArg;
            StackFrame resultMask = context.SecondArg;
            Value[] values = context.Values;
            int testCount = 0;

            for (int maskIndex = resultMask.basePtr, resultIndex = results.basePtr; maskIndex <= resultMask.endPtr; ++maskIndex)
            {
                if (this.test == values[maskIndex].Boolean)
                {
                    bool boolResult = values[resultIndex].Boolean;
                    if (this.test == boolResult)
                    {
                        testCount++;
                    }
                    values[maskIndex].Boolean = boolResult;
                    ++resultIndex;
                }
            }
            return testCount;
        }

#if DEBUG_FILTER
        public override string ToString()
        {
            return string.Format("{0} {1}", base.ToString(), this.test);
        }
#endif
    }

    // 'And' booleans: test is true
    // 'Or' booleans: test is false
    class StartBooleanOpcode : Opcode
    {
        bool test;

        internal StartBooleanOpcode(bool test)
            : base(OpcodeID.StartBoolean)
        {
            this.test = test;
        }

        internal override bool Equals(Opcode op)
        {
            if (base.Equals(op))
            {
                return (((StartBooleanOpcode)op).test == this.test);
            }

            return false;
        }

        internal override Opcode Eval(ProcessingContext context)
        {
            StackFrame sequences = context.TopSequenceArg;
            Value[] values = context.Values;
            StackFrame resultMask = context.TopArg;
            Value[] sequenceBuffer = context.Sequences;

            context.PushSequenceFrame();
            for (int seqIndex = sequences.basePtr; seqIndex <= sequences.endPtr; ++seqIndex)
            {
                NodeSequence sourceSeq = sequenceBuffer[seqIndex].Sequence;
                if (sourceSeq.Count > 0)
                {
                    NodeSequenceItem[] items = sourceSeq.Items;
                    NodeSequence newSeq = null;
                    // Loop over the sequence, selecting those items for which the previous expression returned a result that
                    // matches the test value. Only those items will be processed further
                    // Note that the original position and size information is retained.
                    for (int i = resultMask.basePtr, n = 0; i <= resultMask.endPtr; ++i, ++n)
                    {
                        if (this.test == values[i].Boolean)
                        {
                            if (null == newSeq)
                            {
                                newSeq = context.CreateSequence();
                            }
                            newSeq.AddCopy(ref items[n], NodeSequence.GetContextSize(sourceSeq, n));
                        }
                        else
                        {
                            if (items[n].Last && null != newSeq)
                            {
                                newSeq.Items[newSeq.Count - 1].Last = true; // maintain nodeset boundaries...
                            }
                        }
                    }
                    context.PushSequence((null == newSeq) ? NodeSequence.Empty : newSeq);
                    newSeq = null;
                }
            }

            return this.next;
        }

#if DEBUG_FILTER
        public override string ToString()
        {
            return string.Format("{0} {1}", base.ToString(), this.test);
        }
#endif
    }

    // 'And' booleans: test is true
    // 'Or' booleans: test is false
    class EndBooleanOpcode : ApplyBooleanOpcode
    {
        internal EndBooleanOpcode(Opcode jump, bool test)
            : base(OpcodeID.EndBoolean, jump, test)
        {
        }

        internal override Opcode Eval(ProcessingContext context)
        {
            int matchCount = this.UpdateResultMask(context);
            context.PopFrame();
            context.PopSequenceFrame();
            if (0 == matchCount)
            {
                return this.Jump;
            }

            return this.next;
        }
    }

    class NoOpOpcode : Opcode
    {
        internal NoOpOpcode(OpcodeID id)
            : base(id)
        {
        }
    }

    class BlockEndOpcode : Opcode
    {
        QueryBuffer<Opcode> sourceJumps;

        internal BlockEndOpcode()
            : base(OpcodeID.BlockEnd)
        {
            this.sourceJumps = new QueryBuffer<Opcode>(1);
        }

        internal void DeLinkJump(Opcode jump)
        {
            this.sourceJumps.Remove(jump);
        }

        internal void LinkJump(Opcode jump)
        {
            this.sourceJumps.Add(jump);
        }

        internal override void Remove()
        {
            // Before we can remove this blockEnd from the query tree, we have delink all jumps to it
            while (this.sourceJumps.Count > 0)
            {
                ((JumpOpcode)this.sourceJumps[0]).RemoveJump(this);
            }
            base.Remove();
        }

    }

    class TypecastOpcode : Opcode
    {
        ValueDataType newType;
#if NO
        internal TypecastOpcode(OpcodeID opcode, ValueDataType newType)
            : base(opcode)
        {
            this.newType = newType;
        }
#endif
        internal TypecastOpcode(ValueDataType newType)
            : base(OpcodeID.Cast)
        {
            this.newType = newType;
        }

        internal override bool Equals(Opcode op)
        {
            if (base.Equals(op))
            {
                return (this.newType == ((TypecastOpcode)op).newType);
            }

            return false;
        }

        internal override Opcode Eval(ProcessingContext context)
        {
            StackFrame frame = context.TopArg;
            Value[] values = context.Values;
            for (int i = frame.basePtr; i <= frame.endPtr; ++i)
            {
                values[i].ConvertTo(context, newType);
            }

            return this.next;
        }

#if DEBUG_FILTER
        public override string ToString()
        {
            return string.Format("{0} {1}", base.ToString(), this.newType.ToString());
        }
#endif
    }

    struct BranchContext
    {
        ProcessingContext branchContext;
        ProcessingContext sourceContext;

        internal BranchContext(ProcessingContext context)
        {
            this.sourceContext = context;
            this.branchContext = null;
        }

        internal ProcessingContext Create()
        {
            if (null == this.branchContext)
            {
                this.branchContext = this.sourceContext.Clone();
            }
            else
            {
                this.branchContext.CopyFrom(this.sourceContext);
            }
            return this.branchContext;
        }

        internal void Release()
        {
            if (null != this.branchContext)
            {
                this.branchContext.Release();
            }
        }
    }

    class QueryBranch
    {
        internal Opcode branch;
        internal int id;
#if NO
        internal QueryBranch(Opcode branch)
            : this(branch, int.MinValue)
        {
        }
#endif
        internal QueryBranch(Opcode branch, int id)
        {
            this.branch = branch;
            this.id = id;
        }

        internal Opcode Branch
        {
            get
            {
                return this.branch;
            }
#if NO
            set
            {
                this.branch = value;
            }
#endif
        }

        internal int ID
        {
            get
            {
                return this.id;
            }
        }
    }

    class QueryBranchTable
    {
        int count;
        QueryBranch[] branches;

        internal QueryBranchTable()
            : this(1)
        {
        }

        internal QueryBranchTable(int capacity)
        {
            this.branches = new QueryBranch[capacity];
        }

        internal int Count
        {
            get
            {
                return this.count;
            }
        }

        internal QueryBranch this[int index]
        {
            get
            {
                return this.branches[index];
            }
        }
#if NO
        internal void Add(QueryBranch entry)
        {
            Fx.Assert(null != entry, "");
            this.InsertAt(this.count, entry);
        }
#endif
        internal void AddInOrder(QueryBranch branch)
        {
            // Insert in sorted order always
            int index;
            for (index = 0; index < this.count; ++index)
            {
                // if current node is >= key, we've found the spot
                if (this.branches[index].ID >= branch.ID)
                {
                    break;
                }
            }

            this.InsertAt(index, branch);
        }

        void Grow()
        {
            QueryBranch[] branches = new QueryBranch[this.branches.Length + 1];
            Array.Copy(this.branches, branches, this.branches.Length);
            this.branches = branches;
        }

        public int IndexOf(Opcode opcode)
        {
            for (int i = 0; i < this.count; ++i)
            {
                if (object.ReferenceEquals(opcode, this.branches[i].Branch))
                {
                    return i;
                }
            }
            return -1;
        }

        public int IndexOfID(int id)
        {
            for (int i = 0; i < this.count; ++i)
            {
                if (this.branches[i].ID == id)
                {
                    return i;
                }
            }
            return -1;
        }

#if NO
        public int IndexOfEquals(Opcode opcode)
        {
            for (int i = 0; i < this.count; ++i)
            {
                if (this.branches[i].Branch.Equals(opcode))
                {
                    return i;
                }
            }
            return -1;
        }
#endif
        internal void InsertAt(int index, QueryBranch branch)
        {
            if (this.count == this.branches.Length)
            {
                this.Grow();
            }
            if (index < this.count)
            {
                Array.Copy(this.branches, index, this.branches, index + 1, this.count - index);
            }
            this.branches[index] = branch;
            this.count++;
        }

        internal bool Remove(Opcode branch)
        {
            Fx.Assert(null != branch, "");
            int index = this.IndexOf(branch);
            if (index >= 0)
            {
                this.RemoveAt(index);
                return true;
            }

            return false;
        }

        internal void RemoveAt(int index)
        {
            Fx.Assert(index < this.count, "");
            if (index < this.count - 1)
            {
                Array.Copy(this.branches, index + 1, this.branches, index, this.count - index - 1);
            }
            else
            {
                this.branches[index] = null;
            }
            this.count--;
        }

        internal void Trim()
        {
            if (this.count < this.branches.Length)
            {
                QueryBranch[] branches = new QueryBranch[this.count];
                Array.Copy(this.branches, branches, this.count);
                this.branches = branches;
            }

            for (int i = 0; i < this.branches.Length; ++i)
            {
                if (this.branches[i] != null && this.branches[i].Branch != null)
                {
                    this.branches[i].Branch.Trim();
                }
            }
        }
    }

    class BranchOpcode : Opcode
    {
        OpcodeList branches;

        internal BranchOpcode()
            : this(OpcodeID.Branch)
        {
        }

        internal BranchOpcode(OpcodeID id)
            : base(id)
        {
            this.flags |= OpcodeFlags.Branch;
            this.branches = new OpcodeList(2);
        }

        internal OpcodeList Branches
        {
            get
            {
                return this.branches;
            }
        }

        internal override void Add(Opcode opcode)
        {
            // Add with maximum affinity.. find a similar opcode, if we can, and call its Add method
            for (int i = 0; i < this.branches.Count; ++i)
            {
                if (this.branches[i].IsEquivalentForAdd(opcode))
                {
                    this.branches[i].Add(opcode);
                    return;
                }
            }

            // Ok.. no similar opcode. Add it just like any other branch
            this.AddBranch(opcode);
        }

        internal override void AddBranch(Opcode opcode)
        {
            Fx.Assert(null != opcode, "");

            // Make sure the same opcode doesn't already exist..
            Fx.Assert(-1 == this.branches.IndexOf(opcode), "");
            this.branches.Add(opcode);
            opcode.Prev = this;

            // If this branch is in a conditional, then this new opcode must be added to that conditional..
            if (this.IsInConditional())
            {
                this.LinkToConditional(opcode);
            }
        }

        internal override void CollectXPathFilters(ICollection<MessageFilter> filters)
        {
            for (int i = 0; i < this.branches.Count; ++i)
            {
                this.branches[i].CollectXPathFilters(filters);
            }
        }

        internal override void DelinkFromConditional(Opcode child)
        {
            if (null != this.prev)
            {
                this.prev.DelinkFromConditional(child);
            }
        }
        internal override Opcode Eval(ProcessingContext context)
        {
            QueryProcessor processor = context.Processor;
            SeekableXPathNavigator contextNode = processor.ContextNode;
            int marker = processor.CounterMarker;
            long pos = contextNode.CurrentPosition;
            Opcode branch;
            int i = 0;
            int branchCount = this.branches.Count;
            try
            {
                if (context.StacksInUse)
                {
                    // If we have N branches, eval N-1 in a cloned context and the remainder in the
                    // original one
                    if (--branchCount > 0)
                    {
                        // Evaluate all but the first branch with a clone of the current context
                        // The first branch (right most) can be evaluated with the current context                        
                        BranchContext branchContext = new BranchContext(context); // struct. fast
                        for (; i < branchCount; ++i)
                        {
                            branch = this.branches[i];
                            if (0 != (branch.Flags & OpcodeFlags.Fx))
                            {
                                branch.Eval(context);
                            }
                            else
                            {
                                // This allocates a solitary context and then reuses it repeatedly
                                ProcessingContext newContext = branchContext.Create();
                                while (null != branch)
                                {
                                    branch = branch.Eval(newContext);
                                }
                            }
                            contextNode.CurrentPosition = pos;  // restore the navigator to its original position
                            processor.CounterMarker = marker;   // and the node count marker
                        }
                        branchContext.Release();
                    }

                    // Do the final branch with the existing context
                    branch = branches[i];
                    while (null != branch)
                    {
                        branch = branch.Eval(context);
                    }
                }
                else // since there is nothing on the stack, there is nothing to clone
                {
                    int nodeCountSav = context.NodeCount;
                    for (; i < branchCount; ++i)
                    {
                        branch = branches[i];
                        // Evaluate this branch
                        while (null != branch)
                        {
                            branch = branch.Eval(context);
                        }
                        // Restore the current context to its pristine state, so we can reuse it
                        context.ClearContext();
                        context.NodeCount = nodeCountSav;
                        contextNode.CurrentPosition = pos;
                        processor.CounterMarker = marker;
                    }
                }
            }
            catch (XPathNavigatorException e)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(branches[i]));
            }
            catch (NavigatorInvalidBodyAccessException e)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(branches[i]));
            }
            processor.CounterMarker = marker;

            return this.next;
        }

        internal override bool IsInConditional()
        {
            if (null != this.prev)
            {
                return this.prev.IsInConditional();
            }

            return true;
        }

        internal override void LinkToConditional(Opcode child)
        {
            if (null != this.prev)
            {
                this.prev.LinkToConditional(child);
            }
        }

        /// <summary>
        /// Loop over all branches, trying to locate one that is equal to the given opcode
        /// If the branch is a branch itself, perform the locate recursively.
        /// </summary>
        /// <param name="opcode"></param>
        /// <returns></returns>
        internal override Opcode Locate(Opcode opcode)
        {
            Fx.Assert(!opcode.TestFlag(OpcodeFlags.Branch), "");

            for (int i = 0, count = this.branches.Count; i < count; ++i)
            {
                Opcode branch = this.branches[i];
                if (branch.TestFlag(OpcodeFlags.Branch))
                {
                    // The branch is itself a branch. Since branch opcodes serve as branches in the exection
                    // path for a query, but don't comprise one of the opcodes used to actually perform it, we
                    // recursively try to locate an equivalent opcode inside the branch
                    Opcode subBranch = branch.Locate(opcode);
                    if (null != subBranch)
                    {
                        return subBranch;
                    }
                }
                else if (branch.Equals(opcode))
                {
                    return branch;
                }
            }

            return null;
        }

        internal override void Remove()
        {
            if (0 == this.branches.Count)
            {
                base.Remove();
            }
        }

        internal override void RemoveChild(Opcode opcode)
        {
            Fx.Assert(null != opcode, "");

            if (this.IsInConditional())
            {
                this.DelinkFromConditional(opcode);
            }
            this.branches.Remove(opcode);
            this.branches.Trim();
        }

        internal override void Replace(Opcode replace, Opcode with)
        {
            int i = this.branches.IndexOf(replace);
            if (i >= 0)
            {
                replace.Prev = null;
                this.branches[i] = with;
                with.Prev = this;
            }
        }

        internal override void Trim()
        {
            this.branches.Trim();
            for (int i = 0; i < this.branches.Count; ++i)
            {
                this.branches[i].Trim();
            }
        }
    }

    struct QueryBranchResult
    {
        internal QueryBranch branch;
        int valIndex;

        internal QueryBranchResult(QueryBranch branch, int valIndex)
        {
            this.branch = branch;
            this.valIndex = valIndex;
        }

        internal QueryBranch Branch
        {
            get
            {
                return this.branch;
            }
        }

        internal int ValIndex
        {
            get
            {
                return this.valIndex;
            }
        }
#if NO
        internal void Set(QueryBranch branch, int valIndex)
        {
            this.branch = branch;
            this.valIndex = valIndex;
        }
#endif
    }

    internal class QueryBranchResultSet
    {
        QueryBuffer<QueryBranchResult> results;
        QueryBranchResultSet next;
        internal static SortComparer comparer = new SortComparer();

        internal QueryBranchResultSet()
            : this(2)
        {
        }

        internal QueryBranchResultSet(int capacity)
        {
            this.results = new QueryBuffer<QueryBranchResult>(capacity);
        }

        internal int Count
        {
            get
            {
                return this.results.count;
            }
        }

        internal QueryBranchResult this[int index]
        {
            get
            {
                return this.results[index];
            }
        }

        internal QueryBranchResultSet Next
        {
            get
            {
                return this.next;
            }
            set
            {
                this.next = value;
            }
        }

        internal void Add(QueryBranch branch, int valIndex)
        {
            this.results.Add(new QueryBranchResult(branch, valIndex));
        }

        internal void Clear()
        {
            this.results.count = 0;
        }

        internal void Sort()
        {
            this.results.Sort(QueryBranchResultSet.comparer);
        }

        internal class SortComparer : IComparer<QueryBranchResult>
        {
            public bool Equals(QueryBranchResult x, QueryBranchResult y)
            {
                return x.branch.id == y.branch.id;
            }
            public int Compare(QueryBranchResult x, QueryBranchResult y)
            {
                return x.branch.id - y.branch.id;
            }

            public int GetHashCode(QueryBranchResult obj)
            {
                return obj.branch.id;
            }
        }
    }

    struct BranchMatcher
    {
        int resultCount;
        QueryBranchResultSet resultTable;

        internal BranchMatcher(int resultCount, QueryBranchResultSet resultTable)
        {
            this.resultCount = resultCount;
            this.resultTable = resultTable;
        }

        internal QueryBranchResultSet ResultTable
        {
            get
            {
                return this.resultTable;
            }
        }

        void InitResults(ProcessingContext context)
        {
            context.PushFrame();
            // Push this.resultsCount booleans onto the stack, all set to false
            context.Push(false, this.resultCount);
        }

        internal void InvokeMatches(ProcessingContext context)
        {
            Fx.Assert(null != context, "");

            switch (this.resultTable.Count)
            {
                default:
                    this.InvokeMultiMatch(context);
                    break;

                case 0:
                    break;

                case 1:
                    this.InvokeSingleMatch(context);
                    break;
            }
        }

        void InvokeMultiMatch(ProcessingContext context)
        {
            int marker = context.Processor.CounterMarker;
            BranchContext branchContext = new BranchContext(context);   // struct. quick.
            int resultTableCount = this.resultTable.Count;
            for (int i = 0; i < resultTableCount; )
            {
                QueryBranchResult result = this.resultTable[i];
                QueryBranch branch = result.Branch;
                // Branches can arbitrarily alter context stacks, rendering them unuseable to other branches. 
                // Therefore, before following a branch, we have to clone the context. Cloning is relatively efficient because
                // can avoid allocating memory in most cases. We cannot, unfortunately, avoid Array copies. 
                //
                // Optimization: 
                // We can avoid cloning altogether when we can predict that the branch does NOT tamper with the stack,
                // or does so in a predictable way. If we are sure that we can restore the stack easily after the branch
                // completes, we have no reason to copy the stack.
                ProcessingContext newContext;
                Opcode nextOpcode = branch.Branch.Next;
                if (nextOpcode.TestFlag(OpcodeFlags.NoContextCopy))
                {
                    newContext = context;
                }
                else
                {
                    newContext = branchContext.Create();
                }

                this.InitResults(newContext);

                //
                // Matches are sorted by their branch ID.
                // It is very possible that the a literal matches multiple times, especially when the value being 
                // compared is a sequence. A literal may match multiple items in a single sequence 
                // OR multiple items in multiple sequences. If there were 4 context sequences, the literal may have 
                // matched one item each in 3 of them. The branchID for that literal will be present 3 times in the
                // resultTable.
                // Sorting the matches groups them by their branch Ids. We only want to take the branch ONCE, so now we
                // iterate over all the duplicate matches..
                // result.ValIndex will give us the index of the value that was matched. Thus if the 3rd sequence 
                // matched, ValIndex == 2 (0 based)
                newContext.Values[newContext.TopArg[result.ValIndex]].Boolean = true;
                while (++i < resultTableCount)
                {
                    result = this.resultTable[i];
                    if (branch.ID == result.Branch.ID)
                    {
                        newContext.Values[newContext.TopArg[result.ValIndex]].Boolean = true;
                    }
                    else
                    {
                        break;
                    }
                }
                try
                {
                    newContext.EvalCodeBlock(nextOpcode);
                }
                catch (XPathNavigatorException e)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(nextOpcode));
                }
                catch (NavigatorInvalidBodyAccessException e)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(nextOpcode));
                }
                context.Processor.CounterMarker = marker;
            }
            branchContext.Release();
        }

        internal void InvokeNonMatches(ProcessingContext context, QueryBranchTable nonMatchTable)
        {
            Fx.Assert(null != context && null != nonMatchTable, "");

            int marker = context.Processor.CounterMarker;
            BranchContext branchContext = new BranchContext(context);
            int nonMatchIndex = 0;
            int matchIndex = 0;
            while (matchIndex < this.resultTable.Count && nonMatchIndex < nonMatchTable.Count)
            {
                int compare = this.resultTable[matchIndex].Branch.ID - nonMatchTable[nonMatchIndex].ID;
                if (compare > 0)
                {
                    // Nonmatch < match
                    // Invoke..
                    ProcessingContext newContext = branchContext.Create();
                    this.InvokeNonMatch(newContext, nonMatchTable[nonMatchIndex]);
                    context.Processor.CounterMarker = marker;
                    ++nonMatchIndex;
                }
                else if (0 == compare)
                {
                    ++nonMatchIndex;
                }
                else
                {
                    ++matchIndex;
                }
            }
            // Add remaining
            while (nonMatchIndex < nonMatchTable.Count)
            {
                ProcessingContext newContext = branchContext.Create();
                this.InvokeNonMatch(newContext, nonMatchTable[nonMatchIndex]);
                context.Processor.CounterMarker = marker;
                ++nonMatchIndex;
            }
            branchContext.Release();
        }

        void InvokeNonMatch(ProcessingContext context, QueryBranch branch)
        {
            context.PushFrame();
            context.Push(false, this.resultCount);
            try
            {
                context.EvalCodeBlock(branch.Branch);
            }
            catch (XPathNavigatorException e)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(branch.Branch));
            }
            catch (NavigatorInvalidBodyAccessException e)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(branch.Branch));
            }
        }

        void InvokeSingleMatch(ProcessingContext context)
        {
            int marker = context.Processor.CounterMarker;
            QueryBranchResult result = this.resultTable[0];
            this.InitResults(context);
            context.Values[context.TopArg[result.ValIndex]].Boolean = true;

            try
            {
                context.EvalCodeBlock(result.Branch.Branch.Next);
            }
            catch (XPathNavigatorException e)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(result.Branch.Branch.Next));
            }
            catch (NavigatorInvalidBodyAccessException e)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(result.Branch.Branch.Next));
            }

            context.Processor.CounterMarker = marker;
        }

        internal void Release(ProcessingContext context)
        {
            context.Processor.ReleaseResults(this.resultTable);
        }
    }

    abstract class QueryBranchIndex
    {
        internal abstract int Count
        {
            get;
        }
        internal abstract QueryBranch this[object key]
        {
            get;
            set;
        }

        internal abstract void CollectXPathFilters(ICollection<MessageFilter> filters);

#if NO
        internal abstract IEnumerator GetEnumerator();
#endif
        internal abstract void Match(int valIndex, ref Value val, QueryBranchResultSet results);
        internal abstract void Remove(object key);

        internal abstract void Trim();
    }

    class QueryConditionalBranchOpcode : Opcode
    {
        QueryBranchTable alwaysBranches;
        QueryBranchIndex branchIndex;
        int nextID;

        internal QueryConditionalBranchOpcode(OpcodeID id, QueryBranchIndex branchIndex)
            : base(id)
        {
            Fx.Assert(null != branchIndex, "");
            this.flags |= OpcodeFlags.Branch;
            this.branchIndex = branchIndex;
            this.nextID = 0;
        }

        internal QueryBranchTable AlwaysBranches
        {
            get
            {
                if (null == this.alwaysBranches)
                {
                    this.alwaysBranches = new QueryBranchTable();
                }
                return this.alwaysBranches;
            }
        }
#if NO
        internal QueryBranchIndex BranchIndex
        {
            get
            {
                return this.branchIndex;
            }
        }
#endif
        internal override void Add(Opcode opcode)
        {
            LiteralRelationOpcode literal = this.ValidateOpcode(opcode);
            if (null == literal)
            {
                base.Add(opcode);
                return;
            }

            // Was this literal already added to the index?
            QueryBranch queryBranch = this.branchIndex[literal.Literal];
            if (null == queryBranch)
            {
                // First time. New branch
                this.nextID++;
                queryBranch = new QueryBranch(literal, this.nextID);
                literal.Prev = this;
                this.branchIndex[literal.Literal] = queryBranch;
            }
            else
            {
                Fx.Assert(!object.ReferenceEquals(queryBranch.Branch, literal), "");
                Fx.Assert(literal.ID == queryBranch.Branch.ID, "");
                // literal already exists.. but what follows the literal must be branched
                // Should never get here, but just in case
                queryBranch.Branch.Next.Add(literal.Next);
            }
            literal.Flags |= OpcodeFlags.InConditional;

            this.AddAlwaysBranch(queryBranch, literal.Next);
        }

        internal void AddAlwaysBranch(Opcode literal, Opcode next)
        {
            LiteralRelationOpcode literalOp = this.ValidateOpcode(literal);
            Fx.Assert(null != literalOp, "");
            if (null != literalOp)
            {
                this.AddAlwaysBranch(literalOp, next);
            }
        }

        // Whether or not the given literal matches, we must always take the branch rooted at 'next'
        // Add to the AlwaysBranches table if not already there..
        internal void AddAlwaysBranch(LiteralRelationOpcode literal, Opcode next)
        {
            Fx.Assert(null != literal && null != next, "");

            QueryBranch literalBranch = this.branchIndex[literal.Literal];
            Fx.Assert(null != literalBranch, "");

            this.AddAlwaysBranch(literalBranch, next);
        }

        void AddAlwaysBranch(QueryBranch literalBranch, Opcode next)
        {
            if (OpcodeID.Branch == next.ID)
            {
                BranchOpcode opcode = (BranchOpcode)next;
                OpcodeList branches = opcode.Branches;
                for (int i = 0; i < branches.Count; ++i)
                {
                    Opcode branch = branches[i];
                    if (this.IsAlwaysBranch(branch))
                    {
                        this.AlwaysBranches.AddInOrder(new QueryBranch(branch, literalBranch.ID));
                    }
                    else
                    {
                        branch.Flags |= OpcodeFlags.NoContextCopy;
                    }
                }
            }
            else
            {
                Fx.Assert(!next.TestFlag(OpcodeFlags.Branch), "");
                if (this.IsAlwaysBranch(next))
                {
                    this.AlwaysBranches.AddInOrder(new QueryBranch(next, literalBranch.ID));
                }
                else
                {
                    next.Flags |= OpcodeFlags.NoContextCopy;
                }
            }
        }

        internal virtual void CollectMatches(int valIndex, ref Value val, QueryBranchResultSet results)
        {
            this.branchIndex.Match(valIndex, ref val, results);
        }

        internal override void CollectXPathFilters(ICollection<MessageFilter> filters)
        {
            if (this.alwaysBranches != null)
            {
                for (int i = 0; i < this.alwaysBranches.Count; ++i)
                {
                    this.alwaysBranches[i].Branch.CollectXPathFilters(filters);
                }
            }

            this.branchIndex.CollectXPathFilters(filters);
        }

        internal override Opcode Eval(ProcessingContext context)
        {
            StackFrame arg = context.TopArg;
            int argCount = arg.Count;

            if (argCount > 0)
            {
                QueryBranchResultSet resultSet = context.Processor.CreateResultSet();
                BranchMatcher matcher = new BranchMatcher(argCount, resultSet);
                // Operate on values at the the top frame of the value stack
                // For each source value, find the branch that could be taken
                for (int i = 0; i < argCount; ++i)
                {
                    this.CollectMatches(i, ref context.Values[arg[i]], resultSet);
                }
                // Done with whatever we were testing equality against
                context.PopFrame();
                if (resultSet.Count > 1)
                {
                    // Sort results
                    resultSet.Sort();
                }

                // First, do non-true branches..
                if (null != this.alwaysBranches && this.alwaysBranches.Count > 0)
                {
                    matcher.InvokeNonMatches(context, this.alwaysBranches);
                }

                // Iterate through matches, invoking each matched branch
                matcher.InvokeMatches(context);

                matcher.Release(context);
            }
            else
            {
                context.PopFrame();
            }
            return this.next;
        }

        internal QueryBranch GetBranch(Opcode op)
        {
            if (op.TestFlag(OpcodeFlags.Literal))
            {
                LiteralRelationOpcode relOp = this.ValidateOpcode(op);
                if (null != relOp)
                {
                    QueryBranch branch = this.branchIndex[relOp.Literal];
                    if (null != branch && branch.Branch.ID == op.ID)
                    {
                        return branch;
                    }
                }
            }

            return null;
        }

        bool IsAlwaysBranch(Opcode next)
        {
            Fx.Assert(null != next, "");

            // Opcodes subsequent to matching literals must obviously be branched to.
            // The question is whether we should branch to the opcodes following those literals that do *not* match.
            // Naturally, the answer depends on the sort of opcode that succeeds the literal.
            //
            // If the literal is within a boolean conjunction, the succeeding opcode will either be a JumpIfNot
            // Or a BlockEnd.
            // 
            // -If the JumpIfNot is multiway, then always evaluate if it contains ANY non-result only opcodes.
            // -If JumpIfNot(False) -i.e. AND - only evaluate if the opcode succeeding the jump is NOT a result opcode.
            // -If JumpIfNot(True) - i.e. OR - always evaluate
            // 
            // -If BlockEnd - evaluate only if not followed by a result
            //
            // When branching for matching literals, we push trues onto the ValueStack corresponding to the items that 
            // matched. When branching for non-matching literals, we push ALL FALSE values... and then eval.

            // is it a the termination of a conditional?
            JumpIfOpcode jump = next as JumpIfOpcode;
            if (null != jump)
            {
                // Is the conditional JumpIfNot(False) = i.e. OR? 
                if (!jump.Test)
                {
                    return true;
                }

                // Does the conditional actually jump to anything? Should never be the case, but paranoia demands..
                Opcode jumpTo = jump.Jump;
                if (null == jumpTo)
                {
                    return false;
                }

                // Lets see where the jump will take us
                Opcode postJump;
                if (jumpTo.TestFlag(OpcodeFlags.Branch))
                {
                    // Multiway jump
                    OpcodeList branches = ((BranchOpcode)jumpTo).Branches;
                    for (int i = 0; i < branches.Count; ++i)
                    {
                        postJump = branches[i].Next;
                        if (null != postJump && !postJump.TestFlag(OpcodeFlags.Result))
                        {
                            // There is at least one jump here that leads to a non-result.
                            // For now, this dooms everybody to being branched to, whether or not their respective literals
                            // matched
                            return true;
                        }
                    }
                    return false;
                }

                // single jump
                postJump = jump.Jump.Next;
                if (null != postJump && postJump.TestFlag(OpcodeFlags.Result))
                {
                    return false;
                }

                return true;
            }

            // If the next opcode is a BlockEnd, then only bother processing if what follows the block is not a result
            if (OpcodeID.BlockEnd == next.ID)
            {
                Fx.Assert(null != next.Next, "");
                return (!next.Next.TestFlag(OpcodeFlags.Result));
            }

            // The literal is not inside a boolean conjunction
            // If the literal is not followed by a result, then we must do further processing after the branch
            return (!next.TestFlag(OpcodeFlags.Result));
        }

        /// <summary>
        /// Returns true if this branch can accept 'opcode' being added to it
        /// </summary>
        internal override bool IsEquivalentForAdd(Opcode opcode)
        {
            if (null != this.ValidateOpcode(opcode))
            {
                return true;
            }

            return base.IsEquivalentForAdd(opcode);
        }

        internal override Opcode Locate(Opcode opcode)
        {
            QueryBranch queryBranch = this.GetBranch(opcode);
            if (null != queryBranch)
            {
                return queryBranch.Branch;
            }

            return null;
        }

        internal override void Remove()
        {
            if (null == this.branchIndex || 0 == this.branchIndex.Count)
            {
                base.Remove();
            }
        }

        internal override void RemoveChild(Opcode opcode)
        {
            LiteralRelationOpcode literal = this.ValidateOpcode(opcode);
            Fx.Assert(null != literal, "");

            QueryBranch branch = this.branchIndex[literal.Literal];
            Fx.Assert(null != branch, "");
            this.branchIndex.Remove(literal.Literal);
            branch.Branch.Flags &= (~OpcodeFlags.NoContextCopy);
            if (null != this.alwaysBranches)
            {
                int removeAt = this.alwaysBranches.IndexOfID(branch.ID);
                if (removeAt >= 0)
                {
                    this.alwaysBranches.RemoveAt(removeAt);
                    if (0 == this.alwaysBranches.Count)
                    {
                        this.alwaysBranches = null;
                    }
                }
            }
        }

        internal void RemoveAlwaysBranch(Opcode opcode)
        {
            if (null == this.alwaysBranches)
            {
                return;
            }

            // Note: if the opcodes below are not in the alwaysBranches table, nothing will happen
            // So arbitrary calls are safe - just makes the removal processor slower (we'll speed it up if necessary)
            if (OpcodeID.Branch == opcode.ID)
            {
                OpcodeList branches = ((BranchOpcode)opcode).Branches;
                for (int i = 0; i < branches.Count; ++i)
                {
                    this.alwaysBranches.Remove(branches[i]);
                }
            }
            else
            {
                this.alwaysBranches.Remove(opcode);
            }
            if (0 == this.alwaysBranches.Count)
            {
                this.alwaysBranches = null;
            }
        }

        internal override void Replace(Opcode replace, Opcode with)
        {
            throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new NotImplementedException(SR.GetString(SR.FilterUnexpectedError)));
        }

        internal override void Trim()
        {
            if (this.alwaysBranches != null)
            {
                this.alwaysBranches.Trim();
            }
            this.branchIndex.Trim();
        }

        internal virtual LiteralRelationOpcode ValidateOpcode(Opcode opcode)
        {
            return opcode as LiteralRelationOpcode;
        }
    }
}