This repository has been archived by the owner on Jul 3, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathPegBase.cs
2106 lines (2082 loc) · 73.5 KB
/
PegBase.cs
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
/*Author:Martin.Holzherr;Date:20080922;Context:"PEG Support for C#";Licence:CPOL
* <<History>>
* 20080922;V1.0 created
* 20080929;UTF16BE;Added UTF16BE read support to <<FileLoader.LoadFile(out string src)>>
* <</History>>
*/
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Diagnostics;
using System.Text;
using System;
namespace Peg.Base
{
#region Input File Support
public enum EncodingClass { unicode, utf8, binary, ascii };
public enum UnicodeDetection { notApplicable, BOM, FirstCharIsAscii };
public class FileLoader
{
public enum FileEncoding { none, ascii, binary, utf8, unicode, utf16be, utf16le, utf32le, utf32be, uniCodeBOM };
public FileLoader(EncodingClass encodingClass, UnicodeDetection detection, string path)
{
encoding_ = GetEncoding(encodingClass, detection, path);
path_ = path;
}
public bool IsBinaryFile()
{
return encoding_ == FileEncoding.binary;
}
public bool LoadFile(out byte[] src)
{
src = null;
if (!IsBinaryFile()) return false;
using (BinaryReader brdr = new BinaryReader(File.Open(path_, FileMode.Open,FileAccess.Read)))
{
src = brdr.ReadBytes((int)brdr.BaseStream.Length);
return true;
}
}
public bool LoadFile(out string src)
{
src = null;
Encoding textEncoding = FileEncodingToTextEncoding();
if (textEncoding == null)
{
if (encoding_ == FileEncoding.binary) return false;
using (StreamReader rd = new StreamReader(path_, true))
{
src = rd.ReadToEnd();
return true;
}
}
else
{
if (encoding_ == FileEncoding.utf16be)//UTF16BE
{
using (BinaryReader brdr = new BinaryReader(File.Open(path_, FileMode.Open, FileAccess.Read)))
{
byte[] bytes = brdr.ReadBytes((int)brdr.BaseStream.Length);
StringBuilder s = new StringBuilder();
for (int i = 0; i < bytes.Length; i += 2)
{
char c = (char)(bytes[i] << 8 | bytes[i + 1]);
s.Append(c);
}
src = s.ToString();
return true;
}
}
else
{
using (StreamReader rd = new StreamReader(path_, textEncoding))
{
src = rd.ReadToEnd();
return true;
}
}
}
}
Encoding FileEncodingToTextEncoding()
{
switch (encoding_)
{
case FileEncoding.utf8: return new UTF8Encoding();
case FileEncoding.utf32be:
case FileEncoding.utf32le: return new UTF32Encoding();
case FileEncoding.unicode:
case FileEncoding.utf16be:
case FileEncoding.utf16le: return new UnicodeEncoding();
case FileEncoding.ascii: return new ASCIIEncoding();
case FileEncoding.binary:
case FileEncoding.uniCodeBOM: return null;
default: Debug.Assert(false);
return null;
}
}
static FileEncoding DetermineUnicodeWhenFirstCharIsAscii(string path)
{
using (BinaryReader br = new BinaryReader(File.Open(path, FileMode.Open, FileAccess.Read)))
{
byte[] startBytes = br.ReadBytes(4);
if (startBytes.Length == 0) return FileEncoding.none;
if (startBytes.Length == 1 || startBytes.Length == 3) return FileEncoding.utf8;
if (startBytes.Length == 2 && startBytes[0] != 0) return FileEncoding.utf16le;
if (startBytes.Length == 2 && startBytes[0] == 0) return FileEncoding.utf16be;
if (startBytes[0] == 0 && startBytes[1] == 0) return FileEncoding.utf32be;
if (startBytes[0] == 0 && startBytes[1] != 0) return FileEncoding.utf16be;
if (startBytes[0] != 0 && startBytes[1] == 0) return FileEncoding.utf16le;
return FileEncoding.utf8;
}
}
FileEncoding GetEncoding(EncodingClass encodingClass, UnicodeDetection detection, string path)
{
switch (encodingClass)
{
case EncodingClass.ascii: return FileEncoding.ascii;
case EncodingClass.unicode:
{
if (detection == UnicodeDetection.FirstCharIsAscii)
{
return DetermineUnicodeWhenFirstCharIsAscii(path);
}
else if (detection == UnicodeDetection.BOM)
{
return FileEncoding.uniCodeBOM;
}
else return FileEncoding.unicode;
}
case EncodingClass.utf8: return FileEncoding.utf8;
case EncodingClass.binary: return FileEncoding.binary;
}
return FileEncoding.none;
}
string path_;
public readonly FileEncoding encoding_;
}
#endregion Input File Support
#region Error handling
public class PegException : System.Exception
{
public PegException()
: base("Fatal parsing error ocurred")
{
}
}
public struct PegError
{
internal SortedList<int, int> lineStarts;
void AddLineStarts(string s, int first, int last, ref int lineNo, out int colNo)
{
colNo = 2;
for (int i = first + 1; i <= last; ++i, ++colNo)
{
if (s[i - 1] == '\n')
{
lineStarts[i] = ++lineNo;
colNo = 1;
}
}
--colNo;
}
public void GetLineAndCol(string s, int pos, out int lineNo, out int colNo)
{
for (int i = lineStarts.Count(); i > 0; --i)
{
KeyValuePair<int, int> curLs = lineStarts.ElementAt(i - 1);
if (curLs.Key == pos)
{
lineNo = curLs.Value;
colNo = 1;
return;
}
if (curLs.Key < pos)
{
lineNo = curLs.Value;
AddLineStarts(s, curLs.Key, pos, ref lineNo, out colNo);
return;
}
}
lineNo = 1;
AddLineStarts(s, 0, pos, ref lineNo, out colNo);
}
}
#endregion Error handling
#region Syntax/Parse-Tree related classes
public enum ESpecialNodes { eFatal = -10001, eAnonymNTNode = -1000, eAnonymASTNode = -1001, eAnonymousNode = -100 }
public enum ECreatorPhase { eCreate, eCreationComplete, eCreateAndComplete }
public struct PegBegEnd//indices into the source string
{
public int Length
{
get { return posEnd_ - posBeg_; }
}
public string GetAsString(string src)
{
Debug.Assert(src.Length >= posEnd_);
return src.Substring(posBeg_, Length);
}
public int posBeg_;
public int posEnd_;
}
public class PegNode : ICloneable
{
#region Constructors
public PegNode(PegNode parent, int id, PegBegEnd match, PegNode child, PegNode next)
{
parent_ = parent; id_ = id; child_ = child; next_ = next;
match_ = match;
}
public PegNode(PegNode parent, int id, PegBegEnd match, PegNode child)
: this(parent, id, match, child, null)
{
}
public PegNode(PegNode parent, int id, PegBegEnd match)
: this(parent, id, match, null, null)
{ }
public PegNode(PegNode parent, int id)
: this(parent, id, new PegBegEnd(), null, null)
{
}
#endregion Constructors
#region Public Members
public virtual string GetAsString(string s)
{
return match_.GetAsString(s);
}
public virtual PegNode Clone()
{
PegNode clone= new PegNode(parent_, id_, match_);
CloneSubTrees(clone);
return clone;
}
#endregion Public Members
#region Protected Members
protected void CloneSubTrees(PegNode clone)
{
PegNode child = null, next = null;
if (child_ != null)
{
child = child_.Clone();
child.parent_ = clone;
}
if (next_ != null)
{
next = next_.Clone();
next.parent_ = clone;
}
clone.child_ = child;
clone.next_ = next;
}
#endregion Protected Members
#region Data Members
public int id_;
public PegNode parent_, child_, next_;
public PegBegEnd match_;
#endregion Data Members
#region ICloneable Members
object ICloneable.Clone()
{
return Clone();
}
#endregion
}
internal struct PegTree
{
internal enum AddPolicy { eAddAsChild, eAddAsSibling };
internal PegNode root_;
internal PegNode cur_;
internal AddPolicy addPolicy;
}
public abstract class PrintNode
{
public abstract int LenMaxLine();
public abstract bool IsLeaf(PegNode p);
public virtual bool IsSkip(PegNode p) { return false; }
public abstract void PrintNodeBeg(PegNode p, bool bAlignVertical, ref int nOffsetLineBeg, int nLevel);
public abstract void PrintNodeEnd(PegNode p, bool bAlignVertical, ref int nOffsetLineBeg, int nLevel);
public abstract int LenNodeBeg(PegNode p);
public abstract int LenNodeEnd(PegNode p);
public abstract void PrintLeaf(PegNode p, ref int nOffsetLineBeg, bool bAlignVertical);
public abstract int LenLeaf(PegNode p);
public abstract int LenDistNext(PegNode p, bool bAlignVertical, ref int nOffsetLineBeg, int nLevel);
public abstract void PrintDistNext(PegNode p, bool bAlignVertical, ref int nOffsetLineBeg, int nLevel);
}
public class TreePrint : PrintNode
{
#region Data Members
public delegate string GetNodeName(PegNode node);
string src_;
TextWriter treeOut_;
int nMaxLineLen_;
bool bVerbose_;
GetNodeName GetNodeName_;
#endregion Data Members
#region Methods
public TreePrint(TextWriter treeOut, string src, int nMaxLineLen, GetNodeName GetNodeName, bool bVerbose)
{
treeOut_ = treeOut;
nMaxLineLen_ = nMaxLineLen;
bVerbose_ = bVerbose;
GetNodeName_ = GetNodeName;
src_ = src;
}
public void PrintTree(PegNode parent, int nOffsetLineBeg, int nLevel)
{
if (IsLeaf(parent))
{
PrintLeaf(parent, ref nOffsetLineBeg, false);
treeOut_.Flush();
return;
}
bool bAlignVertical =
DetermineLineLength(parent, nOffsetLineBeg) > LenMaxLine();
PrintNodeBeg(parent, bAlignVertical, ref nOffsetLineBeg, nLevel);
int nOffset = nOffsetLineBeg;
for (PegNode p = parent.child_; p != null; p = p.next_)
{
if (IsSkip(p)) continue;
if (IsLeaf(p))
{
PrintLeaf(p, ref nOffsetLineBeg, bAlignVertical);
}
else
{
PrintTree(p, nOffsetLineBeg, nLevel + 1);
}
if (bAlignVertical)
{
nOffsetLineBeg = nOffset;
}
while (p.next_ != null && IsSkip(p.next_)) p = p.next_;
if (p.next_ != null)
{
PrintDistNext(p, bAlignVertical, ref nOffsetLineBeg, nLevel);
}
}
PrintNodeEnd(parent, bAlignVertical, ref nOffsetLineBeg, nLevel);
treeOut_.Flush();
}
int DetermineLineLength(PegNode parent, int nOffsetLineBeg)
{
int nLen = LenNodeBeg(parent);
PegNode p;
for (p = parent.child_; p != null; p = p.next_)
{
if (IsSkip(p)) continue;
if (IsLeaf(p))
{
nLen += LenLeaf(p);
}
else
{
nLen += DetermineLineLength(p, nOffsetLineBeg);
}
if (nLen + nOffsetLineBeg > LenMaxLine())
{
return nLen + nOffsetLineBeg;
}
}
nLen += LenNodeEnd(p);
return nLen;
}
public override int LenMaxLine() { return nMaxLineLen_; }
public override void
PrintNodeBeg(PegNode p, bool bAlignVertical, ref int nOffsetLineBeg, int nLevel)
{
PrintIdAsName(p);
treeOut_.Write("<");
if (bAlignVertical)
{
treeOut_.WriteLine();
treeOut_.Write(new string(' ', nOffsetLineBeg += 2));
}
else
{
++nOffsetLineBeg;
}
}
public override void
PrintNodeEnd(PegNode p, bool bAlignVertical, ref int nOffsetLineBeg, int nLevel)
{
if (bAlignVertical)
{
treeOut_.WriteLine();
treeOut_.Write(new string(' ', nOffsetLineBeg -= 2));
}
treeOut_.Write('>');
if (!bAlignVertical)
{
++nOffsetLineBeg;
}
}
public override int LenNodeBeg(PegNode p) { return LenIdAsName(p) + 1; }
public override int LenNodeEnd(PegNode p) { return 1; }
public override void PrintLeaf(PegNode p, ref int nOffsetLineBeg, bool bAlignVertical)
{
if (bVerbose_)
{
PrintIdAsName(p);
treeOut_.Write('<');
}
int len = p.match_.posEnd_ - p.match_.posBeg_;
treeOut_.Write("'");
if (len > 0)
{
treeOut_.Write(src_.Substring(p.match_.posBeg_, p.match_.posEnd_ - p.match_.posBeg_));
}
treeOut_.Write("'");
if (bVerbose_) treeOut_.Write('>');
}
public override int LenLeaf(PegNode p)
{
int nLen = p.match_.posEnd_ - p.match_.posBeg_ + 2;
if (bVerbose_) nLen += LenIdAsName(p) + 2;
return nLen;
}
public override bool IsLeaf(PegNode p)
{
return p.child_ == null;
}
public override void
PrintDistNext(PegNode p, bool bAlignVertical, ref int nOffsetLineBeg, int nLevel)
{
if (bAlignVertical)
{
treeOut_.WriteLine();
treeOut_.Write(new string(' ', nOffsetLineBeg));
}
else
{
treeOut_.Write(' ');
++nOffsetLineBeg;
}
}
public override int
LenDistNext(PegNode p, bool bAlignVertical, ref int nOffsetLineBeg, int nLevel)
{
return 1;
}
int LenIdAsName(PegNode p)
{
string name = GetNodeName_(p);
return name.Length;
}
void PrintIdAsName(PegNode p)
{
string name = GetNodeName_(p);
treeOut_.Write(name);
}
#endregion Methods
}
#endregion Syntax/Parse-Tree related classes
#region Parsers
public abstract class PegBaseParser
{
#region Data Types
public delegate bool Matcher();
public delegate PegNode Creator(ECreatorPhase ePhase, PegNode parentOrCreated, int id);
#endregion Data Types
#region Data members
protected int srcLen_;
protected int pos_;
protected bool bMute_;
protected TextWriter errOut_;
protected Creator nodeCreator_;
protected int maxpos_;
PegTree tree;
#endregion Data members
public virtual string GetRuleNameFromId(int id)
{//normally overridden
switch (id)
{
case (int)ESpecialNodes.eFatal: return "FATAL";
case (int)ESpecialNodes.eAnonymNTNode: return "Nonterminal";
case (int)ESpecialNodes.eAnonymASTNode: return "ASTNode";
case (int)ESpecialNodes.eAnonymousNode: return "Node";
default: return id.ToString();
}
}
public virtual void GetProperties(out EncodingClass encoding, out UnicodeDetection detection)
{
encoding = EncodingClass.ascii;
detection = UnicodeDetection.notApplicable;
}
public int GetMaximumPosition()
{
return maxpos_;
}
protected PegNode DefaultNodeCreator(ECreatorPhase phase, PegNode parentOrCreated, int id)
{
if (phase == ECreatorPhase.eCreate || phase == ECreatorPhase.eCreateAndComplete)
return new PegNode(parentOrCreated, id);
else
{
if (parentOrCreated.match_.posEnd_ > maxpos_)
maxpos_ = parentOrCreated.match_.posEnd_;
return null;
}
}
#region Constructors
public PegBaseParser(TextWriter errOut)
{
srcLen_ = pos_ = 0;
errOut_ = errOut;
nodeCreator_ = DefaultNodeCreator;
}
#endregion Constructors
#region Reinitialization, TextWriter access,Tree Access
public void Construct(TextWriter Fout)
{
srcLen_ = pos_ = 0;
bMute_ = false;
SetErrorDestination(Fout);
ResetTree();
}
public void Rewind() { pos_ = 0; }
public void SetErrorDestination(TextWriter errOut)
{
errOut_ = errOut == null ? new StreamWriter(System.Console.OpenStandardError())
: errOut;
}
#endregion Reinitialization, TextWriter access,Tree Access
#region Tree root access, Tree Node generation/display
public PegNode GetRoot() { return tree.root_; }
public void ResetTree()
{
tree.root_ = null;
tree.cur_ = null;
tree.addPolicy = PegTree.AddPolicy.eAddAsChild;
}
void AddTreeNode(int nId, PegTree.AddPolicy newAddPolicy, Creator createNode, ECreatorPhase ePhase)
{
if (bMute_) return;
if (tree.root_ == null)
{
tree.root_ = tree.cur_ = createNode(ePhase, tree.cur_, nId);
}
else if (tree.addPolicy == PegTree.AddPolicy.eAddAsChild)
{
tree.cur_ = tree.cur_.child_ = createNode(ePhase, tree.cur_, nId);
}
else
{
tree.cur_ = tree.cur_.next_ = createNode(ePhase, tree.cur_.parent_, nId);
}
tree.addPolicy = newAddPolicy;
}
void RestoreTree(PegNode prevCur, PegTree.AddPolicy prevPolicy)
{
if (bMute_) return;
if (prevCur == null)
{
tree.root_ = null;
}
else if (prevPolicy == PegTree.AddPolicy.eAddAsChild)
{
prevCur.child_ = null;
}
else
{
prevCur.next_ = null;
}
tree.cur_ = prevCur;
tree.addPolicy = prevPolicy;
}
public bool TreeChars(Matcher toMatch)
{
return TreeCharsWithId((int)ESpecialNodes.eAnonymousNode, toMatch);
}
public bool TreeChars(Creator nodeCreator, Matcher toMatch)
{
return TreeCharsWithId(nodeCreator, (int)ESpecialNodes.eAnonymousNode, toMatch);
}
public bool TreeCharsWithId(int nId, Matcher toMatch)
{
return TreeCharsWithId(nodeCreator_, nId, toMatch);
}
public bool TreeCharsWithId(Creator nodeCreator, int nId, Matcher toMatch)
{
int pos = pos_;
if (toMatch())
{
if (!bMute_)
{
AddTreeNode(nId, PegTree.AddPolicy.eAddAsSibling, nodeCreator, ECreatorPhase.eCreateAndComplete);
tree.cur_.match_.posBeg_ = pos;
tree.cur_.match_.posEnd_ = pos_;
}
return true;
}
return false;
}
public bool TreeNT(int nRuleId, Matcher toMatch)
{
return TreeNT(nodeCreator_, nRuleId, toMatch);
}
public bool TreeNT(Creator nodeCreator, int nRuleId, Matcher toMatch)
{
if (bMute_) return toMatch();
PegNode prevCur = tree.cur_, ruleNode;
PegTree.AddPolicy prevPolicy = tree.addPolicy;
int posBeg = pos_;
AddTreeNode(nRuleId, PegTree.AddPolicy.eAddAsChild, nodeCreator, ECreatorPhase.eCreate);
ruleNode = tree.cur_;
bool bMatches = toMatch();
if (!bMatches) RestoreTree(prevCur, prevPolicy);
else
{
ruleNode.match_.posBeg_ = posBeg;
ruleNode.match_.posEnd_ = pos_;
tree.cur_ = ruleNode;
tree.addPolicy = PegTree.AddPolicy.eAddAsSibling;
nodeCreator(ECreatorPhase.eCreationComplete, ruleNode, nRuleId);
}
return bMatches;
}
public bool TreeAST(int nRuleId, Matcher toMatch)
{
return TreeAST(nodeCreator_, nRuleId, toMatch);
}
public bool TreeAST(Creator nodeCreator, int nRuleId, Matcher toMatch)
{
if (bMute_) return toMatch();
bool bMatches = TreeNT(nodeCreator, nRuleId, toMatch);
if (bMatches)
{
if (tree.cur_.child_ != null && tree.cur_.child_.next_ == null && tree.cur_.parent_ != null)
{
if (tree.cur_.parent_.child_ == tree.cur_)
{
tree.cur_.parent_.child_ = tree.cur_.child_;
tree.cur_.child_.parent_ = tree.cur_.parent_;
tree.cur_ = tree.cur_.child_;
}
else
{
PegNode prev;
for (prev = tree.cur_.parent_.child_; prev != null && prev.next_ != tree.cur_; prev = prev.next_)
{
}
if (prev != null)
{
prev.next_ = tree.cur_.child_;
tree.cur_.child_.parent_ = tree.cur_.parent_;
tree.cur_ = tree.cur_.child_;
}
}
}
}
return bMatches;
}
public bool TreeNT(Matcher toMatch)
{
return TreeNT((int)ESpecialNodes.eAnonymNTNode, toMatch);
}
public bool TreeNT(Creator nodeCreator, Matcher toMatch)
{
return TreeNT(nodeCreator, (int)ESpecialNodes.eAnonymNTNode, toMatch);
}
public bool TreeAST(Matcher toMatch)
{
return TreeAST((int)ESpecialNodes.eAnonymASTNode, toMatch);
}
public bool TreeAST(Creator nodeCreator, Matcher toMatch)
{
return TreeAST(nodeCreator, (int)ESpecialNodes.eAnonymASTNode, toMatch);
}
public virtual string TreeNodeToString(PegNode node)
{
return GetRuleNameFromId(node.id_);
}
public void SetNodeCreator(Creator nodeCreator)
{
Debug.Assert(nodeCreator != null);
nodeCreator_ = nodeCreator;
}
#endregion Tree Node generation
#region PEG e1 e2 .. ; &e1 ; !e1 ; e? ; e* ; e+ ; e{a,b} ; .
public bool And(Matcher pegSequence)
{
PegNode prevCur = tree.cur_;
PegTree.AddPolicy prevPolicy = tree.addPolicy;
int pos0 = pos_;
bool bMatches = pegSequence();
if (!bMatches)
{
pos_ = pos0;
RestoreTree(prevCur, prevPolicy);
}
return bMatches;
}
public bool Peek(Matcher toMatch)
{
int pos0 = pos_;
bool prevMute = bMute_;
bMute_ = true;
bool bMatches = toMatch();
bMute_ = prevMute;
pos_ = pos0;
return bMatches;
}
public bool Not(Matcher toMatch)
{
int pos0 = pos_;
bool prevMute = bMute_;
bMute_ = true;
bool bMatches = toMatch();
bMute_ = prevMute;
pos_ = pos0;
return !bMatches;
}
public bool PlusRepeat(Matcher toRepeat)
{
int i;
for (i = 0; ; ++i)
{
int pos0 = pos_;
if (!toRepeat())
{
pos_ = pos0;
break;
}
}
return i > 0;
}
public bool OptRepeat(Matcher toRepeat)
{
for (; ; )
{
int pos0 = pos_;
if (!toRepeat())
{
pos_ = pos0;
return true;
}
}
}
public bool Option(Matcher toMatch)
{
int pos0 = pos_;
if (!toMatch()) pos_ = pos0;
return true;
}
public bool ForRepeat(int count, Matcher toRepeat)
{
PegNode prevCur = tree.cur_;
PegTree.AddPolicy prevPolicy = tree.addPolicy;
int pos0 = pos_;
int i;
for (i = 0; i < count; ++i)
{
if (!toRepeat())
{
pos_ = pos0;
RestoreTree(prevCur, prevPolicy);
return false;
}
}
return true;
}
public bool ForRepeat(int lower, int upper, Matcher toRepeat)
{
PegNode prevCur = tree.cur_;
PegTree.AddPolicy prevPolicy = tree.addPolicy;
int pos0 = pos_;
int i;
for (i = 0; i < upper; ++i)
{
if (!toRepeat()) break;
}
if (i < lower)
{
pos_ = pos0;
RestoreTree(prevCur, prevPolicy);
return false;
}
return true;
}
public bool Any()
{
if (pos_ < srcLen_)
{
++pos_;
return true;
}
return false;
}
#endregion PEG e1 e2 .. ; &e1 ; !e1 ; e? ; e* ; e+ ; e{a,b} ; .
}
public class PegByteParser : PegBaseParser
{
#region Data members
protected byte[] src_;
PegError errors;
#endregion Data members
#region PEG optimizations
public sealed class BytesetData
{
public struct Range
{
public Range(byte low, byte high) { this.low = low; this.high = high; }
public byte low;
public byte high;
}
System.Collections.BitArray charSet_;
bool bNegated_;
public BytesetData(System.Collections.BitArray b)
: this(b, false)
{
}
public BytesetData(System.Collections.BitArray b, bool bNegated)
{
charSet_ = new System.Collections.BitArray(b);
bNegated_ = bNegated;
}
public BytesetData(Range[] r, byte[] c)
: this(r, c, false)
{
}
public BytesetData(Range[] r, byte[] c, bool bNegated)
{
int max = 0;
if (r != null) foreach (Range val in r) if (val.high > max) max = val.high;
if (c != null) foreach (int val in c) if (val > max) max = val;
charSet_ = new System.Collections.BitArray(max + 1, false);
if (r != null)
{
foreach (Range val in r)
{
for (int i = val.low; i <= val.high; ++i)
{
charSet_[i] = true;
}
}
}
if (c != null) foreach (int val in c) charSet_[val] = true;
bNegated_ = bNegated;
}
public bool Matches(byte c)
{
bool bMatches = c < charSet_.Length && charSet_[(int)c];
if (bNegated_) return !bMatches;
else return bMatches;
}
}
/* public class BytesetData
{
public struct Range
{
public Range(byte low, byte high) { this.low = low; this.high = high; }
public byte low;
public byte high;
}
protected System.Collections.BitArray charSet_;
bool bNegated_;
public BytesetData(System.Collections.BitArray b, bool bNegated)
{
charSet_ = new System.Collections.BitArray(b);
bNegated_ = bNegated;
}
public BytesetData(byte[] c, bool bNegated)
{
int max = 0;
foreach (int val in c) if (val > max) max = val;
charSet_ = new System.Collections.BitArray(max + 1, false);
foreach (int val in c) charSet_[val] = true;
bNegated_ = bNegated;
}
public BytesetData(Range[] r, byte[] c, bool bNegated)
{
int max = 0;
foreach (Range val in r) if (val.high > max) max = val.high;
foreach (int val in c) if (val > max) max = val;
charSet_ = new System.Collections.BitArray(max + 1, false);
foreach (Range val in r)
{
for (int i = val.low; i <= val.high; ++i)
{
charSet_[i] = true;
}
}
foreach (int val in c) charSet_[val] = true;
}
public bool Matches(byte c)
{
bool bMatches = c < charSet_.Length && charSet_[(int)c];
if (bNegated_) return !bMatches;
else return bMatches;
}
}*/
#endregion PEG optimizations
#region Constructors
public PegByteParser()
: this(null)
{
}
public PegByteParser(byte[] src):base(null)
{
SetSource(src);
}
public PegByteParser(byte[] src, TextWriter errOut):base(errOut)
{
SetSource(src);
}
#endregion Constructors
#region Reinitialization, Source Code access, TextWriter access,Tree Access
public void Construct(byte[] src, TextWriter Fout)
{
base.Construct(Fout);
SetSource(src);
}
public void SetSource(byte[] src)
{
if (src == null) src = new byte[0];
src_ = src; srcLen_ = src.Length;
errors.lineStarts = new SortedList<int, int>();
errors.lineStarts[0] = 1;
}
public byte[] GetSource() { return src_; }
#endregion Reinitialization, Source Code access, TextWriter access,Tree Access
#region Setting host variables
public bool Into(Matcher toMatch,out byte[] into)
{
int pos = pos_;
if (toMatch())
{
int nLen = pos_ - pos;
into= new byte[nLen];
for(int i=0;i<nLen;++i){
into[i] = src_[i+pos];
}
return true;
}
else
{
into = null;
return false;
}
}
public bool Into(Matcher toMatch,out PegBegEnd begEnd)
{
begEnd.posBeg_ = pos_;
bool bMatches = toMatch();
begEnd.posEnd_ = pos_;
return bMatches;
}
public bool Into(Matcher toMatch,out int into)
{
byte[] s;
into = 0;
if (!Into(toMatch,out s)) return false;
into = 0;
for (int i = 0; i < s.Length; ++i)
{
into <<= 8;
into |= s[i];
}
return true;
}
public bool Into(Matcher toMatch,out double into)
{
byte[] s;
into = 0.0;
if (!Into(toMatch,out s)) return false;
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
string sAsString = encoding.GetString(s);
if (!System.Double.TryParse(sAsString, out into)) return false;
return true;
}
public bool BitsInto(int lowBitNo, int highBitNo,out int into)
{
if (pos_ < srcLen_)
{
into = (src_[pos_] >> (lowBitNo - 1)) & ((1 << highBitNo) - 1);
++pos_;
return true;
}
into = 0;
return false;
}
public bool BitsInto(int lowBitNo, int highBitNo, BytesetData toMatch, out int into)
{
if (pos_ < srcLen_)
{
byte value = (byte)((src_[pos_] >> (lowBitNo - 1)) & ((1 << highBitNo) - 1));
++pos_;