0

How do I write following BNF Grammar in ANTLR?

literal = "{" number "}" CRLF *CHAR8
        ; Number represents the number of CHAR8s

For example {6}\r\nLENGTH should be mapped to "LENGTH" string.

Will following work?

literal: 
   | '{' ('0'..'9')+ '}\r\n'  
        {  
            // C# Code for Lexer
            Text = Text.Trim();
            int n = int.Parse(Text.Substring(1,Text.Length-2));
            Text = "";
            for(int i=0;i<n;i++){
               input.Consume();
            }            
        }
  ;

I am getting this working as a Lexer rule, but problem is I am getting mismatched token, I am not getting token as literal.

Akash Kava
  • 39,066
  • 20
  • 121
  • 167
  • Would a solution that does this in 2 steps be ok? e.g. pass two checks that the number to the left and the string to the right are the same length. – user7116 May 30 '12 at 14:32
  • I didnt get you, I dont know much about ANTLR and I just saw its generated C# and based on that I have written this, the problem is, it has few methods such as LeaveRule etc, I want to know what shall be my last statement? LeaveRule() should be called or not. – Akash Kava May 30 '12 at 14:35
  • @SwDevMan81 why C# was removed from here? The target language for ANTLR grammar is C# – Akash Kava May 30 '12 at 15:35
  • @BartKiers, sorry, typo, yes I corrected it to 6 chars. – Akash Kava May 30 '12 at 15:38

1 Answers1

0

This solution works correctly,

literal: 
   | '{' ('0'..'9')+ '}\r\n'  
        {  
            // C# Code for Lexer
            Text = Text.Trim();
            int n = int.Parse(Text.Substring(1,Text.Length-2));
            Text = "";
            for(int i=0;i<n+1;i++){
               Text += (char) input.LA(1);
               input.Consume();
            }            
        }
  ;

Text += (char)input.LA(1); was missing and for some reason, we have to count i from 0 to n+1.

Akash Kava
  • 39,066
  • 20
  • 121
  • 167