views:

153

answers:

2

I have to define the grammar of a file like the one shown below.

//Sample file
NameCount = 4
Name = a
Name = b
Name = c
Name = d
//End of file

Now I am able to define tokens for NameCount and Name. But i have to define the file structure including the valid number of instances of token Name , which is the value after NameCount. I have the value parsed and converted into an integer and stored in a variable at global scope of the grammar (say in variable nc).

How to define in grammar that Name should repeat exactly nc times?

+1  A: 

I'm not sure this is a context free grammar. If it isn't, you cannot tell ANTLR to parse the language.

boutta
+4  A: 

This cannot be expressed in the grammar itself. If the number was fix you could express the number of expected tokens. But the token stream changes based on the value. What you can do is to include this into the lexer/parser combination. But you cannot create this construct by just the plain grammar syntax. You probably want something along the lines of

grammar test;

@members {
  private int count = 0;
  private int names = 0;
}

file
    : count (name)+
      {
        if (count != names) throw new Exception("");
      }
    ;

count
    : 'NameCount' EQ Number
      {
        count = Integer.parseInt($Number.text);
      }
    ;

name
    : 'Name' EQ Value
      {
        names++;
      }
...
tcurdt