[antlr-interest] if-then-else - Grammar generates faulty parser code
poornima_prakash
poornima.prakash at cgi.com
Thu Apr 22 00:16:48 PDT 2004
We have a classic 'if-then-else' rule in the grammar file. The
problem we are facing is with the ANTLR versions 2.7.2 and 2.7.4rc1.
The 'rule' in the grammar file is defined as follows :
rule options { defaultErrorHandler = true;} :
ifPart thenPart
(options {warnWhenFollowAmbig = false;} :
elsePart
)?;
ifPart: "if"^ LPARENTHESIS! conditional_expression RPARENTHESIS!;
thenPart : "then"^ stmt_blk;
elsePart :"else"^ stmt_blk;
Since the 'else' part is optional, when we give an input rule with
only the 'if-then' and without the 'else', AST is not generated
correctly. It stops at the root node!
However, if we manipulate the generated C# code, AST is correctly
generated. We have to move the line "rule_AST = currentAST.root;" in
the generated sources such that it is traversed even when only 'if-
then' input rule is given.
To be more precise, the line "rule_AST = currentAST.root;" at the
end of the 'try' block in the below (automatically generated parser)
code has to be moved into the 'default' case of switch-case for the
correct AST to get generated.
public void rule() //throws RecognitionException, TokenStreamException
{
returnAST = null;
ASTPair currentAST = new ASTPair();
AST rule_AST = null;
try { // for error handling
ifPart();
astFactory.addASTChild(currentAST, returnAST);
thenPart();
astFactory.addASTChild(currentAST, returnAST);
{
switch ( LA(1) )
{
case LITERAL_else:
{
elsePart();
astFactory.addASTChild
(currentAST, returnAST);
break;
}
case LITERAL_if:
....
case IDENTIFIER:
{
break;
}
default:
{
throw new NoViableAltException
(LT(1), getFilename());
}
}
}
rule_AST = currentAST.root;
}
catch (RecognitionException ex)
{...
}
returnAST = rule_AST;
}
Please advice the required grammar change such that the AST gets
generated properly without moving around the generated code.
Looking forward to your reply.
regards,
Poornima and Raghu.
Yahoo! Groups Links
<*> To visit your group on the web, go to:
http://groups.yahoo.com/group/antlr-interest/
<*> To unsubscribe from this group, send an email to:
antlr-interest-unsubscribe at yahoogroups.com
<*> Your use of Yahoo! Groups is subject to:
http://docs.yahoo.com/info/terms/
More information about the antlr-interest
mailing list