Question

I am using JavaCC to print an AST in a particular format. I need it to be like this :

LetNode( Identier(X), ExprNode( PlusNode( IntegerLiteral(8), IntegerLiteral(2) ))) 

but I am getting:

Start(LetNode(Identifier(x)(ExprNode(IntegerLiteral(5)(PlusNode(IntegerLiteral(5)()))

I am using the dump method to print this:

public void dump(String prefix) {
  System.out.print(toString(prefix));
  System.out.print("(");
  if (children != null) {

    for (int i = 0; i < children.length; ++i) {
      SimpleNode n = (SimpleNode)children[i];
      if (n != null) {
        n.dump(prefix +"");
      }
    }
    System.out.print(")");
  }
}

}

The output without any modification is :

Start
  Sxl
   Statement
    VariableDecl
     Identifier
     Type
     Expression
      SimpleExpression
       Term
        Factor
         Literal
          IntegerLiteral
       AdditiveOp
       Term
        Factor
         Literal
          IntegerLiteral

My method:

void AdditiveOp():
{}  
{
   (Plus() /*#Add(2)*/ | Minus() | Or())

}

void Plus():
{
}
{
  (< PLUS >)
  #PlusNode
}

If I remove the /* */ it does not work as it says it expects something else not +

Any help would be greatly appreciated!

Was it helpful?

Solution

The usual way to make an AST with JJT for an expression grammar is to do something like this

void AdditiveExpression() #void :
{ Token t ; }
{
  MultiplicativeExpression()
  (  "+"  MultiplicativeExpression()  #Add(2)
  |  "-"  MultiplicativeExpression()  #Subtract(2)   
  )*
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top