Search code examples
antlrantlrworks

Write in a file in ANTLRWorks


I am writing a parser using the ANTLR framework. I want to write in a file, so I use this code, but I do not know where I should close the file?

@header
{
    import java.io.*;
}

main:{ 

  BufferedWriter out = null;
    try{ 
  FileWriter fstream = new FileWriter("output.txt");
  out = new BufferedWriter(fstream);

  }

  catch (Exception e){
  System.err.println("Error: " + e.getMessage());
  }

  };


    p1  :   p2 {out.write("this is p1");}
        ;

   p2 ......

Solution

  • If main is the entry point of your grammar, you would close the stream at the end of that rule:

    grammar T;
    
    @header {
      import java.io.*;
    }
    
    @members {
      OutputStream out = null;
    
      void before() {
        // initialize 'out' here
      }
    
      void after() {
        // close 'out' here
      }
    }
    
    main
     : {before();}
       p1 EOF
       {after();}
     ;
    
    p1
     : p2 {out.write("this is p1");}
     ;
    
    p2
     : ...
     ;
    

    You could even provide empty implementations of your methods inside the @members block:

    @members {
      OutputStream out;
    
      void before() {}
    
      void after() {}
    }
    

    and override/implement them in the listener/visitor classes to minimize target specific code inside the grammar itself.