From 49c5ca908eca0ef1837fdb3e4168c7e9b5dbbd0c Mon Sep 17 00:00:00 2001 From: Kraemerd <Dominic_Daniel.Kraemer@Student.Reutlingen-University.de> Date: Mon, 9 Jan 2023 12:08:03 +0100 Subject: [PATCH] implemented the evaluator, can handle all operations (variables are not working yet) --- expressions.txt | 10 +++++--- src/Application.java | 2 ++ src/Evaluator.java | 59 +++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 66 insertions(+), 5 deletions(-) diff --git a/expressions.txt b/expressions.txt index 55a3a7c..ce8c319 100644 --- a/expressions.txt +++ b/expressions.txt @@ -1,4 +1,6 @@ -1 + x*y^2 - (31 * x)-y -1 + x^2 - (3 * x) -2-x + 0.5*x^2 - 1 -(5*2-(5^2)+3*(201.01-15)) \ No newline at end of file +5 +x +4+2 +3+(2^3) +2*2*2+3 +(23+2*(2*3))-5 \ No newline at end of file diff --git a/src/Application.java b/src/Application.java index f185a6a..096051b 100644 --- a/src/Application.java +++ b/src/Application.java @@ -41,7 +41,9 @@ public class Application { try { Parser.Expression exp = parser.parse(tokens); ASTPrinter printer = new ASTPrinter(); + Evaluator evaluator = new Evaluator(); System.out.println("Printing: '" + printer.visit(exp) + "'"); + System.out.println("Evaluating: '" + evaluator.visit(exp) + "'"); } catch (ParserException e) { System.out.println(e.getMessage()); diff --git a/src/Evaluator.java b/src/Evaluator.java index 4599b70..2c65e1b 100644 --- a/src/Evaluator.java +++ b/src/Evaluator.java @@ -1,2 +1,59 @@ -public class Evaluator { +public class Evaluator implements Visitor<Double>{ + + @Override + public Double visit(final Parser.BinaryOperation binaryOP) { + double result = binaryOP.leftExpression.accept(this); + double rOperand = binaryOP.rightExpression.accept(this); + switch (binaryOP.operator.charAt(0)) { + case '+': + result += rOperand; + break; + case '-': + result -= rOperand; + break; + case '*': + result *= rOperand; + break; + case '/': + if (rOperand != 0) { + result /= rOperand; + } + else { + result = result; + //throw new ArithmeticException("Arithmetic Error: division by zero detected"); + } + break; + case '^': + for(int i=1; i<rOperand; i++) { + result = result*result; + } + break; + default: + throw new RuntimeException("SematicError: unknown operand found in AST: " + + binaryOP.operator); + } + return result; + } + + @Override + public Double visit(final Parser.Variable variable) { + return 0.0; + } + + @Override + public Double visit(final Parser.Number number) { + return Double.valueOf(number.digits); + } + + @Override + public Double visit(final Parser.Decimal decimal) { + return Double.valueOf(decimal.afterDot.digits + "." + decimal.beforeDot.digits); + } + + public double visit(final Parser.Expression ast) { + if(ast==null) { + return 0.0; + } + return ast.accept(this); + } } -- GitLab