Search code examples
antlrantlr3antlrworks

Generating AST from ANTLR grammar


For the question and the grammar suggested by @BartKiers (Thank you!), I added the options block to specify the output to be

options{
language=Java;
output=AST;
ASTLabelType=CommonTree;
}

However, I am not able to figure out how to access the output i.e. AST. I need to traverse through the tree and process each operation that was specified in the input.


Using your example here, I am trying to implement rules returning values. However, I am running into following errors:

relational    returns [String val]                   
        :  STRINGVALUE ((operator)^ term)?
            {val = $STRINGVALUE.text + $operator.text + $term.text; }
                                    ;

term returns [String rhsOperand]                    
        :  QUOTEDSTRINGVALUE  {rhsOperand = $QUOTEDSTRINGVALUE.text;}
                                    |  NUMBERVALUE               {rhsOperand = $NUMBERVALUE.text; }
                                    | '(' condition ')'
                                     ;

Compilation Error:

Checking Grammar RuleGrammarParser.g...
\output\RuleGrammarParser.java:495: cannot find symbol
symbol  : variable val
location: class RuleGrammarParser
            val = (STRINGVALUE7!=null?STRINGVALUE7.getText():null) + (operator8!=null?input.toString(operator8.start,operator8.stop):null) + (term9!=null?input.toString(term9.start,term9.stop):null); 
            ^
\output\RuleGrammarParser.java:612: cannot find symbol
symbol  : variable rhsOperand
location: class RuleGrammarParser
                    rhsOperand = (QUOTEDSTRINGVALUE10!=null?QUOTEDSTRINGVALUE10.getText():null);
                    ^
\output\RuleGrammarParser.java:632: cannot find symbol
symbol  : variable rhsOperand
location: class RuleGrammarParser
                    rhsOperand = (NUMBERVALUE11!=null?NUMBERVALUE11.getText():null); 
                    ^
3 errors

Can you please help me understand why this fails to compiler?


Added the pastebin: http://pastebin.com/u1Bv3L0A


Solution

  • By simply adding output=AST to the options section you don't create a AST, but a flat, 1 dimensional list of tokens. To mark certain tokens as root (or children), you need to do a bit of work.

    Checkout this answer which explains how to create a proper AST and get access to the tree the parser then produces (the CommonTree tree in the main method of the answer I mentioned).

    Note that you can safely remove language=Java;: by default the target language is Java (no harm in leaving it there though).