[antlr-interest] Writing out the source code

stefan stefan at amiq.ro
Mon May 23 05:30:19 PDT 2005


On Monday 23 May 2005 14:54, Serafettin Senturk wrote:
>  Hello,
>
>  I have got my transformed tree(AST) by the help of tree parser. Does
> anybody have an idea how i can now write this AST as a source code in an
> external file? again using another tree parser or how?
You may inherit the tree parser grammar you use now. The new, inherited, 
grammar looks, from a structural point of view, identical with the old one. 
Now you must stuff actions that take the parameters values from the rules and 
put them in some string templates. As you can see below:

OriginalGrammar extends TreeParser;

program:
    #(PROGRAM some_declaration_1 some_declaration_2)
   ;

and, new, modified grammar looks like:

NewGrammar extends OriginalGrammar;

program returns [StringTemplate res = null]
{
   StringTemplate decl_1 = null, decl_2 = null;
} :
    #(PROGRAM id:ID decl_1=some_declaration_1 decl_2=some_declaration_2)
   {
          res = SomeStringTemplateFactory.getStringTemplate("my_program");
          res.setAttribute("id", id.getText());
          res.setAttribute("declaration_1", decl_1);
          res.setAttribute("declaration_2", decl_2);
          // printing action
          System.out.println("->", res.toString());
          // saving action
         BufferedWriter _bw = new BufferedWriter(new FileWriter("path"));
         res.write(SomeStringTemplateFactory.getStringTemplateWriter(_bw));
         _bw.flush();
         _bw.close();
   }
   ;

   The rule "program" is the top/entry rule of your tree, while the 
"declaration_#" are other rules.
   Class "SomeStringTemplateFactory" can be a custom factory or the one 
provided by the string-template package.
   Each node in tree grammar will have a different string template associated 
with it in order to accomodate the different language structures.

    The  template file may look like :

group my_root_group;

my_program(id, declaration_1, declaration_2) ::=<<
MY_PROGRAM $id$ is {
        // my first declaration
        $declaration_1$ ;
        // some coments
        // second, funny, declaration
        HAHAHA 
              $declaration_2$
        AHAHAH
}
>>

      Other usefull information you may find at : 
http://www.codegeneration.net/tiki-read_article.php?articleId=77
       For more info on string templates look at: www.stringtemplate.org
       For more info on how to stuff actions in tree parser see antlr manual.
>
>   Regards,
>  Serafettin


More information about the antlr-interest mailing list