Javacc : nested-if-statements

890 views Asked by At

I generated a parser by JavaCC. Then, I would count the number of nested ifs in my method. My File .jjt is :

// TestParser.jjt
PARSER_BEGIN(TestParser)

public class TestParser {
  public static void main(String[] args) throws ParseException {
    TestParser parser = new TestParser(new java.io.StringReader(args[0]));
    SimpleNode root = parser.program();
    root.dump("");
  }
}

PARSER_END(TestParser)


TOKEN : { <id : ["a"-"z","A"-"Z","_"] (["a"-"z","A"-"Z","0"-"9","_"])* }
 /* Reserved words */
 TOKEN  :
 { < IF > | <begin> | <end> | < THEN > | < ELSEIF >|  <STRING> |  < ENDIF > |...}


SimpleNode MyProgram() #PROGRAM :
{}
 {
 (MyMethod ())*   {return jjtThis;}

 }


void MyMethod () #MyMethod : {}
 {
 <begin> id() "(" (Argument ())* ")" {}
 (Statement ()) *
  <end>
 }


Token id() #ID:
{
  Token t;
}
{
t=<ID> {jjtThis.value = t.image; return t;}
}

 void Argument() #argument : {}
 {
 <String>  id()
 <int>  id()
 }

 void statement () #statement : {}
 {
 ifElseStatement ()
 // here other statement

 }
 void ifElseStatement () #ifElseStatement :{}
 {
   < IF > BooleanStructure() < THEN >
   (
     statement ()
   )*
   (
     < ELSEIF > BooleanStructure() < THEN >
     (
       statement ()
     )*
   )*
     < ELSE >
     (
       statement ()
     )*

   < ENDIF >
 }
 }

I can generated the AST for input file stream. But, My question how I can traverse Tree by Design VISITOR Because I want Count nested If statement. Thank you in advance

1

There are 1 answers

4
Theodore Norvell On

Use the VISITOR=true option. That will generate an accept method for each node class and will create an interface that your visitor class should implement. See the manual at https://javacc.java.net/doc/JJTree.html .

If you also use MULTI=true, the interface is more extensive.