Search code examples
javacompiler-constructionjavacc

SimpleNode child in JJTree


I read in a tutorial that when you do something like that :

SimpleNode Program() #Program : {} 
{
    (Class_decl())* <EOF>

    { return jjtThis; }
}

it should create a Programm class which inherits from SimpleNode (once you compile with jjtree), but in my case it doesn't create such as class. Do I have to create it myself or am I missing something ?

Thanks


Solution

  • Are you first using jjtree on your grammar (before javacc)? It works fine with me:

    file: Test.jjt

    options {
      MULTI=true;
      NODE_PREFIX="";
    }
    
    PARSER_BEGIN(Test)
    public class Test {
      public static void main(String[] args) throws Exception {
        Test parser = new Test(new java.io.StringReader("class A; class B;"));
        SimpleNode root = parser.Program();
        root.dump("");
      }
    }
    PARSER_END(Test)
    
    TOKEN :
    {
         < CLASS : "class" >
      |  < SCOL  : ";" >
      |  < ID    : (["a"-"z","A"-"Z"])+ >
    }
    
    SKIP :
    {
      " " | "\t" | "\r" | "\n"
    }
    
    SimpleNode Program() #Program : 
    {} 
    {
      (Class_decl())* <EOF> {return jjtThis;}
    }
    
    void Class_decl() #ClassDecl :
    {}
    {    
      <CLASS> <ID> <SCOL>
    }
    

    And then the commands:

    jjtree Test.jjt
    javacc Test.jj
    

    which generates the following Java source files:

    ClassDecl.java
    JJTTestState.java
    Node.java
    Program.java
    SimpleNode.java
    TestTreeConstants.java
    

    And both ClassDecl and Program extend SimpleNode:

    /* Generated By:JJTree: Do not edit this line. Program.java Version 4.3 */
    /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
    public
    class Program extends SimpleNode {
      ...
    }
    
    /* Generated By:JJTree: Do not edit this line. ClassDecl.java Version 4.3 */
    /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
    public
    class ClassDecl extends SimpleNode {
      ...
    }
    

    Compiling all source files and running the Test class:

    javac -cp . *.java
    java -cp . Test
    

    which will print:

    Program
     ClassDecl
     ClassDecl
    

    (i.e. Program is the root with two ClassDecl children)

    Tested with Java Compiler Compiler Version 5.0.