[antlr-interest] Help with AST

Thomas Zangl - Home thomas at tzis.net
Sun Apr 22 14:24:11 PDT 2007


 
Dear List!

I created a simple grammer based upon the pascal grammer in the dragon
book. Let's consider this rule:

(This are the options:
class PascalParser extends Parser;
options {
  k = 2;                           // two token lookahead
  exportVocab=Pascal;              // Call its vocabulary "Pascal"
  codeGenMakeSwitchThreshold = 999;  // Some optimizations
  codeGenBitsetTestThreshold = 999;
  defaultErrorHandler = true;      // Do generate parser error handlers
  buildAST = true;
  ASTLabelType = "org.cb.PascalAST";
}
)

program:   PROGRAM^<AST=org.cb.PROGRAMNode> ID args SEM!
			declerations
			subprogram_declerations
			compound_statement
			DOT
    ;      
    
args: (LPAREN^<AST=org.cb.ARGNode> identifier_list RPAREN!)?;
identifier_list: ID<AST=org.cb.TEMPNode> (COMMA! ID<AST=org.cb.TEMPNode>)*;
declerations: (VAR^<AST=org.cb.VARNode> (identifier_list COLON! type
SEM^)*)?; type: standard_type
      | ARRAY LBRACK NUM TYPELIST NUM RBRACK OF standard_type ;
standard_type: INTEGER<AST=org.cb.INTEGERNode> | REAL;
subprogram_declerations: (subprogram_decleration SEM!)*;
subprogram_decleration: subprogram_head declerations compound_statement;

Here are my questions:

What does the ^ and the ! mean? 
How can I create an AST which looks like this:

VAR  -> Variable1 (of type standard_type)
    |-> Variable2 (of type standard_type2)
etc.?

So, the VAR node is the root (lets call it VARLIST) and each children is
a decleration (lets call it VARIABLE) which has a type. Sample pascal
code would be: 

var
  intOne, intTwo: Integer;
  floatOne, floatTwo: Real;

The desired tree would be:
VARLIST -> VAR(intOne, Integer)
        |-> VAR(intTwo, Integer)
        |-> VAR(floatOne, Real)
        |-> VAR(floatTwo, Real)

How to define this in ANTLR?

The next step would be some kind of visitor pattern (or is it called
treewalker in antlr?) which traverses a given AST. I need to react on
each kind of statement: e.g. I need to print the program name when I
encounter a PROGRAMNODE, I need to collect all children and its type if
I encounter a VARLIST node, etc.

Please help! I would really appriciate source code and samples which
clear up things. Please be as verbose as possible. I read a lot of
ANTLR docs but they are more confusing then helpful. 

Best regards,
-- 
----------------------------------------------------------------
,yours Thomas Zangl, Bakk.rer.soc.oec. - thomas at tzis.net -
- Freelancer - IT Consulting & Software Development -
- Student of Software Development-Economy (Master) -


More information about the antlr-interest mailing list