[antlr-interest] How to serialize a AST
    David Marín Carreño 
    dmarin at sice.com
       
    Tue Sep 15 00:30:02 PDT 2009
    
    
  
Hello all.
 
I am developing a calculation framework for my firm using ANTLR3 and Java.
 
I want to serialize an AST for reusing it a lot of times, so this way I can
save parsing time for each calculation.
 
I have developed a CommonTree derived class ICalcTree that implements
Serialize, and another class ICalcTreeAdaptor derived from
CommonTreeAdaptor.
 
In parser options, I have:
 
      output = AST;
      ASTLabelType = ICalcTree;
      language = Java;
 
The program uses the parser this way:
 
String formula = "a=1+2";
      
      Reader reader = new CharArrayReader(formula.toCharArray());
      ICalcLexer lexer = new ICalcLexer(new ANTLRReaderStream(reader));
      CommonTokenStream cts = new CommonTokenStream(lexer);
      ICalcParser tokenParser = new ICalcParser(cts);
        
      TreeAdaptor adaptor = new ICalcTreeAdaptor();
      tokenParser.setTreeAdaptor(adaptor);
      
      ICalcParser.formula_return parserResult =
            tokenParser.formula(); // start rule method
        
      reader.close();
      ICalcTree ast = (ICalcTree) parserResult.getTree();
            
      // Serialize
      
      ByteArrayOutputStream bs = new ByteArrayOutputStream();
      ObjectOutputStream os = new ObjectOutputStream(bs);
      os.writeObject(ast);
      os.close();
      
      byte[] buf = bs.toByteArray();
      String serialized = StringUtils.byteArrayToHexString(buf);
            
      
      // Unserialize
      
      byte[] buf_unserialized =
StringUtils.hexStringToByteArray(serialized);
      ByteArrayInputStream bi = new ByteArrayInputStream(buf_unserialized);
      ObjectInputStream ois = new ObjectInputStream(bi);
      try {
            ICalcTree new_ast = new ICalcTree();
            new_ast = (ICalcTree) ois.readObject();
            System.out.println(new_ast.toStringTree());
      } catch (ClassNotFoundException e) {
            e.printStackTrace();
      }
 
It always print nil, for whatever formula string. 
What am I doing wrong? How can I serialize the AST so it can be reused many
times?
 
Thank you for your assistance.
 
 
David Marín Carreño 
S.I.C.E. 
Dirección Técnica. 
Tfno 91 623 22 30
E-mail: dmarin at sice.com
 
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20090915/fd9ef891/attachment.html 
    
    
More information about the antlr-interest
mailing list