Write in a file in ANTLRWorks

182 views Asked by At

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 ......
1

There are 1 answers

2
Bart Kiers On BEST ANSWER

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.