How do I use ANTLR v3 from the command line?
You can run ANTLRWorks and tell it to generate the output code or you can run ANTLR directly from the commandline with:
$ java -jar antlr-3.1.2.jar mygrammar.g
or
$ java -cp antlr-3.1.2.jar org.antlr.Tool mygrammar.g
Better yet, add the jar antlr-3.1.2.jar to your CLASSPATH
.
Running ANTLR with no parameters shows you:
usage: java org.antlr.Tool [args] file.g [file2.g file3.g ...] -o outputDir specify output directory where all output is generated -fo outputDir same as -o but force even files with relative paths to dir -lib dir specify location of token files -depend generate file dependencies -report print out a report about the grammar(s) processed -print print out the grammar without actions -debug generate a parser that emits debugging events -profile generate a parser that computes profiling information -nfa generate an NFA for each rule -dfa generate a DFA for each decision point -message-format name specify output style for messages -verbose generate ANTLR version and other information -X display extended argument list
For example, consider how to make the LL-star example from the examples tarball you can get at http://www.antlr.org/download/examples-v3.tar.gz.
$ cd examples-v3/java/LL-star $ java org.antlr.Tool SimpleC.g $ javac *.java
In above command, we are considering ANTLR3 jar lies in your classpath.
For input:
char c; int x; void bar(int x); int foo(int y, char d) { int i; for (i=0; i<3; i=i+1) { x=3; y=5; } }
you will see output as follows:
$ java Main input bar is a declaration foo is a definition
What if I want to test my parser without generating code? Easy. Just run ANTLR in interpreter mode. It can't execute your actions, but it can create a parse tree from your input to show you how it would be matched. Use the org.antlr.tool.Interp main class. In the following, I interpret simplec.g on t.c, which contains "int x;"
$ java org.antlr.tool.Interp simplec.g WS program t.c ( <grammar SimpleC> ( program ( declaration ( variable ( type [@0,0:2='int',<14>,1:0] ) ( declarator [@2,4:4='x',<2>,1:4] ) [@3,5:5=';',<5>,1:5] ) ) ) )
where I have formatted the output to make it more readable. I have told it to ignore all WS tokens.