[antlr-interest] AST - don't get it

John B. Brodie jbb at acm.org
Wed Nov 8 07:07:39 PST 2006


Manu :-

>I have understood why is good to build an AST but I don't understand
>exactly how the tree builder operators work. For example, I'd expect
>the following grammar to generate an AST for the entry: 123 * 456
>like:
>
>(START (* 123 456))
>
>but instead it generates:
>
>(NIL (START (* 456)))
>
>where did the 123 go?

....grammar snipped...

your grammar works just fine for me.
e.g. input: 123 * 456
gets tree:  (START (* 123 456) 

maybe there is some setup missing in the Main? here is my Main.java:

//----------begin
import java.io.*;
import java.util.*;

import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.*;

class Main {

   private static final String [] x = new String[]{
      "123 * 456", "1+2", "3*4+5", "8*8*8*8+9+10*11"
   };

   // Custom adaptor to create MyAST node type. will need this adaptor
   // when we override CommonTree with our own AST type.
   //private static final TreeAdaptor adaptor = new CommonTreeAdaptor() {
   //      public Object create(Token payload) {
   //         return new MyAST(payload);
   //      }
   //   };

   public static void main(String[] args) {
      for (int i=0; i < x.length; ++i) {
         try {
            ExpressionsLexer lexer =
               new ExpressionsLexer(new ANTLRStringStream(x[i]));
            CommonTokenStream tokens = new CommonTokenStream(lexer);
            Expressions parser = new Expressions(tokens);
            //parser.setTreeAdaptor(adaptor); // set up our custom AST.
            Expressions.s_return r = parser.s();
            System.out.format("tree:%s%n",((Tree)r.tree).toStringTree());
         } catch(Exception e) {
            e.printStackTrace();
         }
      }
   }
}
//----------end

Hope this helps...
   -jbb


More information about the antlr-interest mailing list