Is it possible to use ANTLR internally in a Java program and use custom classes to execute actual operations ? I would like to be able to parse simple expressions and execute custom operations for them defined in my own Java classes.
Sample expression :
(( AB1 op1 BC2) op2 BB )
AB1, BC2 and BB represent custom Java classes for example MyObj. op1 and op2 are very simple operations and could be thought as + or -
Let's say I have:
interface Operation {
public MyObj operation(MyObj obj1, MyObj obj2);
}
class SomeOperation implements Operation {
public MyObj operation(MyObj obj1, MyObj obj2) {
};
}
class Some2Operation implements Operation {
public MyObj operation(MyObj obj1, MyObj obj2) {
};
}
SomeOperation refers to op1 and Some2Operation refers to op2.
Before evaluating the expression of course actual objects for AB1, BC2 and BB are assigned.
If there's easier/simpler way to accomplish this than using ANTLR please let me know.
EDIT: Continues here...
grammar MyTest;
ID: [a-z]+;
Operator_I: 'I';
Operator_U: 'U';
prog: (expr)* #myProg;
expr: expr op=(Operator_I | Operator_U) expr #myExpr
| ID #myID
| '(' expr ')' #myWithPar
;
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.tree.TerminalNode;
import java.util.*;
public class EvalVisitor extends MyTestBaseVisitor<Value> {
@Override
public Value visitMyProg(MyTestParser.MyProgContext ctx) {
// TODO Auto-generated method stub
System.out.println("prog:"+ctx.getText());
return super.visitMyProg(ctx);
}
@Override
public Value visitMyWithPar(MyTestParser.MyWithParContext ctx) {
// TODO Auto-generated method stub
System.out.println("par:"+ctx.getText());
return super.visitMyWithPar(ctx);
}
@Override
public Value visitMyID(MyTestParser.MyIDContext ctx) {
// TODO Auto-generated method stub
System.out.println("id:"+ctx.getText());
return super.visitMyID(ctx);
}
@Override
public Value visitMyExpr(MyTestParser.MyExprContext ctx) {
// TODO Auto-generated method stub
System.out.println("expr:"+ctx.getText());
return super.visitMyExpr(ctx);
}
private Map<String, Value> memory = new HashMap<String, Value>();
private Map<String, Value> values = new HashMap<String, Value>();
public EvalVisitor() {
values.put("a", new Value(new Double(5)));
values.put("u", new Value(new Double(9)));
}
}
public static void main(String[] args) throws Exception {
MyTestLexer lexer = new MyTestLexer(new ANTLRFileStream("c:\\test.mu"));
MyTestParser parser = new MyTestParser(new CommonTokenStream(lexer));
ParseTree tree = parser.prog();
EvalVisitor visitor = new EvalVisitor();
visitor.visit(tree);
}
test.mu contains:
(aIu)U(aUu)
output of the program:
prog:(aIu)U(aUu)
expr:(aIu)U(aUu)
par:(aIu)
expr:aIu
id:a
id:u
par:(aUu)
expr:aUu
id:a
id:u