Thursday, December 3, 2015

ANTLR quickstart

He's a resource I wrote for those of you wanted to get started with ANTLR, but cut through the BS red tape and get straight to writing grammars! Here it is:

I spent a lot of time trying to get ANTLR in usable shape, and I found the documentation dreadful. So allow me to lay out a much easier alternative to using ANTLR right out of the box, that doesn't require finnicking with system variables that never work.

This may not be the most "flexible" route, but is certainly the quickest one in my experience. The instructions are usable in both UNIX and Windows.



  1. Download the java jdk.After you have it installed you *should* be able to invoke the "java" command from your command prompt. test it using "java -version". If you get some kind of output from that, then great!
  2. Download the ANTLR complete jar.There are two antlr sites in an attempt to separate ANTLR3 from ANTLR4.
    If you want ANTLR4, go to antlr.org
    If you want ANTLR3, go to antlr3.org
    In either case, download the complete jar to a location you wouldn't mind using it.
  3. Test installationIn your command prompt move to the directory that contains the complete jar.
    try the command

    java -cp antlr-x.y.z-complete.jar org.antlr.Tool

    in ANTLR3, or in ANTLR4,

    java -cp antlr-x.y.z-complete.jar org.antlr.v4.Tool

    This command should work, and return options for ANTLR.
    The cp argument means you can you specify CLASSPATH within the command, removing
    the additional step of fooling around with system variables.

  4. Test output
    Use the included "Exp.g" grammar taken from a stackoverflow question and run the following command in ANTLR3

    java -cp antlr-x.y.z-complete.jar org.antlr.Tool Exp.g

    or in ANTLR4

    java -cp antlr-x.y.z-complete.jar org.antlr.v4.Tool Exp.g

    If you're using your own grammar, make sure that the filename matches the first line, e.g. grammar css = css.g

  5. Test different target.In your grammar, add the line

    options{language = C;}

    where "C" is whatever target language you'd want. I'm typically concerned with C or C++
    output, so I use "C" or "Cpp", though ANTLR4 doesn't target C or CPP.
    Run the same command again, and check that it ran correctly and output matches the desired filetype.

  6. Design your grammar
    Congratulations. If the step before worked, than you have everything you need to start doing *actual work* with ANTLR! I hope this was helpful in getting you started, and not hung up on installing stuff. 

Edit:
I found myself also need to check out antlrworks to see how my grammar is structured. As of 1.5.2, try

java -jar antlrworks-1.5.2-complete.jar org.antlr.Tool <grammar.g>


"Installing things is the hardest part of programming."

No comments:

Post a Comment