Reputation: 17
How should look the code that after inserting one equation gives me a result and parsing tree? In my result user has to write the equation two times, because it uses two parsers, that share tokens. Here is the beginning of my code:
Calc parser = new Calc(System.in);
while (true)
{
System.out.println("Input data:");
try
{
System.out.print("Enter an expression like \"1+(2|3+3)*4|8;\" to generate tree :");
Exp result = Calc.FinalTree();
System.out.print("Enter an expression like \"1+(2|3+3)*4|8;\" to calculate:");
String r2 = Calc.Final();
/*Exp result = new Calc(new java.io.StringReader(args[0])).FinalTree();
String r2 = new Calc(new java.io.StringReader(args[0])).Final();
System.out.println(result);
*/
System.out.println("Syntax is OK. \n Tree:" + result + "\n Calc value:" + r2);
Upvotes: 0
Views: 709
Reputation: 370397
Apparently you are defining two versions of every rule in your grammar: one version that creates an AST and one that calculates the result directly. Don't do that.
Instead you should only keep the versions that produce the AST and scrap the others. To evaluate the AST, you can then either add an eval
method to your AST classes or use the visitor pattern. Then the code in your question could be written like this:
System.out.print("Enter an expression like \"1+(2|3+3)*4|8;\" to generate tree :");
Exp result = Calc.FinalTree();
String r2 = result.eval();
System.out.println("Syntax is OK. \n Tree:" + result + "\n Calc value:" + r2);
Or this:
System.out.print("Enter an expression like \"1+(2|3+3)*4|8;\" to generate tree :");
Exp result = Calc.FinalTree();
String r2 = new Evaluator().visit(result);
System.out.println("Syntax is OK. \n Tree:" + result + "\n Calc value:" + r2);
Upvotes: 2