Click here to Skip to main content
15,884,473 members
Articles / Containers / Virtual Machine

Parsing Expression Grammar Support for C# 3.0 Part 1 - PEG Lib and Parser Generator

Rate me:
Please Sign up or sign in to vote.
4.95/5 (49 votes)
7 Oct 2008CPOL40 min read 202.7K   2.1K   118  
Introduction to the parsing method PEG with library and parser generator
<<Grammar Name="BER" 
          encoding_class="binary"
          reference="http://en.wikipedia.org/wiki/Basic_encoding_rules"
          comment="Minimal tree generating BER decoder"
>>

{
   int tag,length,n,@byte;
   bool init_()     {tag=0;length=0;           return true;}
   bool add_Tag_()  {tag*=128;tag+=n;          return true;}
   bool addLength_(){length*=256;length+=@byte;return true;}
}

[1] ProtocolDataUnit: TLV;
[2] ^^TLV:  init_
     ( &BITS<6,#1> Tag ( #x80  CompositeDelimValue  #0#0 / Length CompositeValue )
     / Tag Length PrimitiveValue
     );
[3] Tag: OneOctetTag / MultiOctetTag / FATAL<"illegal TAG">;
[4] ^^OneOctetTag:   !BITS<1-5,#b11111> BITS<1-5,.,:tag>;
[5] ^^MultiOctetTag: . (&BITS<8,#1> BITS<1-7,.,:n> add_Tag_)* BITS<1-7,.,:n> add_Tag_;
[6] Length :   OneOctetLength / MultiOctetLength 
             / FATAL<"illegal LENGTH">;
[7] ^^OneOctetLength: &BITS<8,#0> BITS<1-7,.,:length>;
[8]^^MultiOctetLength: &BITS<8,#1> BITS<1-7,.,:n> ( .:byte addLength_){:n};
[9]^^PrimitiveValue: .{:length} / FATAL<"BER input ends before VALUE ends">;
[10]^^CompositeDelimValue: (!(#0#0) TLV)*;
[11]^^CompositeValue
{
     int len;
     PegBegEnd begEnd;
     bool save_()  {len= length;return true;}
     bool at_end_(){return len<=0;}
     bool decr_()  {len-= begEnd.posEnd_-begEnd.posBeg_;return len>=0;} 
}   :  save_ (!at_end_ TLV:begEnd 
              (decr_/FATAL<"illegal length">))*;
<</Grammar>>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Switzerland Switzerland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions