0

I've created an ANTLR Grammar that properly makes trees of the file type associated with it.

Now what? I don't really get how I make this .g file now parse something. How do I make it do it in my file system and what does it parse it to? Goal is to turn these files (some of it) into JSON format. Any suggestions or clarification, been reading a lot of tutorials, I feel dull because I can't seem to get what I'm looking for out of them.

I'm programming in JAVA and on ANTLR 3.4.

Jono
  • 3,393
  • 6
  • 33
  • 48
  • In case you want to get a better understanding of ANTLR, see: http://stackoverflow.com/questions/278480/antlr-tutorials – Bart Kiers Jun 13 '12 at 06:18

1 Answers1

1

To read and parse from the file system you would write something like:

MyLexer lex = new MyLexer(new ANTLRFileStream(args[0]));
CommonTokenStream tokens = new CommonTokenStream(lex);
MyParser parser = new MyParser(tokens);

try {
   parser.expr();
} catch (RecognitionException e)  {
   e.printStackTrace();
}

(Depends on your output language, of course)

Larry OBrien
  • 8,484
  • 1
  • 41
  • 75
  • I've done that, but I can't get it to work properly with the full object. I can get parser.oneOfMyOtherObjects() to parse but not a full file. Could you tell me more on how I would turn that "parsed" content into a json format? – Jono Jun 12 '12 at 20:28
  • Well, there are a few different ways to specify the action-on-parse, but typically you'd specify it in your .g file rules, with something like : foo returns [String result] : *some pattern* { $result = convertAPatternIntoAJSONObject($String); } ; (You would have your own pattern and you would write your own convertAPatternIntoAJSonObject() functions) – Larry OBrien Jun 12 '12 at 21:01
  • So let me clarify, heres a more comprehensive example: rule : Value (Value | Int)* Something ; What would I do with this? would I just put rule : Value (Value | Int)* Something returns [SomeFunction Value Int] ; Or what? – Jono Jun 12 '12 at 23:34
  • You put the action code inside {} brackets; that will end up being in-lined into the parser and called on recognition. I highly recommend the book "The Definitive ANTLR Reference" available from http://pragprog.com/book/tpantlr/the-definitive-antlr-reference – Larry OBrien Jun 12 '12 at 23:42