akaya
akaya

Reputation: 1140

ANTLR Recursion

When I execute the below grammar with the input (3), I obtain this parse tree:

enter image description here

It doesn't recognize the closing parentheses. What might be the problem

term 
    :  IDENT | '(' term ')'  | INTEGER
    ;

INTEGER : '0'..'9'+;
IDENT : ('a'..'z' | 'A'..'Z')('a'..'z' | 'A'..'Z' | '0'..'9')*;
WS : (' ' | '\t' | '\r' | '\n' | '\f')+{$channel = HIDDEN;};

Upvotes: 1

Views: 444

Answers (2)

Bart Kiers
Bart Kiers

Reputation: 170148

There's no problem with your grammar. It looks like you're using the Eclipse ANTLR-plugin, which in its turn uses the interpreter from ANTLRWorks. This interpreter is notoriously buggy: if you get unexpected behavior, always run a manual test, or use ANTLRWorks' debugger, which debugs the input "(3)" like this:

enter image description here

To start the debugger in ANTLRWors, choose menu Run >> Debug, or press CTL + D.

Upvotes: 1

Jimmy
Jimmy

Reputation: 6171

I think this might be a bug in the UI. I think the parser is seeing the ). Have you tried invoking the parser from Java?

public static void main(String[] args)
    throws Exception
{
    // TODO Auto-generated method stub
    ANTLRStringStream strstrm = new ANTLRStringStream("(3)");
    ffLexer lex = new ffLexer(strstrm);
    CommonTokenStream tokStrm = new CommonTokenStream(lex);
    ffParser prs = new ffParser(tokStrm);
    prs.term();

}

If you add an action to your term rule:

term 
    :  IDENT | a='('   term b=')'  {System.out.println($a.text + " " + $b.text);} | INTEGER
    ;

You should get the output

( )

Also, if you create another parser rule:

prog: term+;

and then give the input (3)(4)(5) the parse tree is as expected

Upvotes: 1

Related Questions