These are the steps to follow to setup Antlr v3.3 on Ubuntu 10.04
- Download the antlrworks-1.4.2.jar
- Add antlrworks-1.4.2.jar to the CLASSPATH variable. For example: export CLASSPATH=.:/path/to/jar/antlrworks-1.4.2.jar
- Create a simple grammar called Expr.g. It's contents are:
prog: stat+ ;
stat: expr NEWLINE
| ID '=' expr NEWLINE { System.out.println("you entered a statement!"); }
| NEWLINE
;
expr: multExpr (('+'|'-') multExpr)*
;
multExpr
: atom ('*' atom)*
;
atom: INT
| ID
| '(' expr ')'
;
ID : ('a'..'z'|'A'..'Z')+ ;
INT : '0'..'9' ;
NEWLINE : '\r'? '\n' ;
WS : (' '|'\t'|'\n'|'\r')+ { skip(); } ;
4. Create a java file called Test.java that will call the objects created by Antlr3. Test.java's contents are:
import java.io.*;
import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
public class Test {
public static void main(String args[]) throws Exception {
ExprLexer lex = new ExprLexer(new ANTLRInputStream(System.in));
CommonTokenStream tokens = new CommonTokenStream(lex);
ExprParser parser = new ExprParser(tokens);
parser.prog();
}
}
5. Compile the antlr grammar and Test.java file as follows:
java org.antlr.Tool Expr.g
javac *.java
6. Test your grammer by then typing:
java Test
and entering this expression:
a=1+2
followed by ctrl-d. This should result in the this statement appearing:
you entered a statement!