Here is a complete grammar that evaluates expressions containing +, -, * and variable assignments. A simple hash table is used to store variable values.
The tutorial requires the current depot version of ANTLR 3.0, i.e. the version must be later than 3.0 beta 5.
And here is the main program to execute the parser:
import org.antlr.runtime.*;
public class Test {
public static void main(String[] args) throws Exception {
ANTLRInputStream input = new ANTLRInputStream(System.in);
ExprLexer lexer = new ExprLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
ExprParser parser = new ExprParser(tokens);
parser.prog();
}
}
Run ANTLR on the grammar and compile:
java org.antlr.Tool Expr.g
javac Test.java ExprLexer.java ExprParser.java
Here is a sample run:
What if you want to build trees instead? Here is a grammar that builds trees instead of evaluating the expressions:
And here is the tree grammar that will read the trees and evaluate the expressions.
Here is the main program:
import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
public class Test {
public static void main(String[] args) throws Exception {
ANTLRInputStream input = new ANTLRInputStream(System.in);
ExprLexer lexer = new ExprLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
ExprParser parser = new ExprParser(tokens);
ExprParser.prog_return r = parser.prog();
CommonTree t = (CommonTree)r.getTree();
CommonTreeNodeStream nodes = new CommonTreeNodeStream(t);
Eval walker = new Eval(nodes);
walker.prog();
}
}
and a sample run:
On generating the EvalTreeParser.java I get
.... value = Integer.parseInt($INT.text);
within the expr() method. Can you tell me what I'm doing wrong.
Thanks, a lot!
Matthias