diff --git a/src/main/ASTPrinter.java b/src/main/ASTPrinter.java index 10669f24f21640f8f627bac93c2015ec2e3a16a8..118fb24440dd13b2641614b9017c7db79256e68f 100644 --- a/src/main/ASTPrinter.java +++ b/src/main/ASTPrinter.java @@ -1,13 +1,32 @@ package main; +/** + * <h1>The ASTPrinter</h1> + * The ASTPrinter class creates a String out of an AST(represented through an Expression object) + * It prints it in a form the Evaluator class can work with it, it isn't primarily designed for + * returning a String that is perfect for human readability (e.g. Pow(x,3) would be printed instead of x^3) + * + * @version 1.0 + * @since 09.01.2023 + */ public class ASTPrinter implements Visitor<String>{ + + /** + * Builds a String representation of a given BinaryOperation + * It gets a String representation of its left and right Expressions (which may result in a + * recursive call) and combines them into one String together with the operator + * @param binaryOP The BinaryOperation that should be printed into a String + * @return String Returns the String that was build + */ @Override public String visit(final Parser.BinaryOperation binaryOP) { StringBuffer sb = new StringBuffer(); + //adds left bracket if the BinaryOperation is capsuled if(binaryOP.capsuled) { sb.append("("); } if(binaryOP.operator.contains("^")) { + //Exponents will be printed in the form of Pow(basis, exponent) so the Evaluator can work with it sb.append("Pow("); sb.append(binaryOP.leftExpression.accept(this)); sb.append(","); @@ -15,36 +34,53 @@ public class ASTPrinter implements Visitor<String>{ sb.append(")"); } else { + //Adds the String representations of the left expression, operator and right expression sb.append(binaryOP.leftExpression.accept(this)); sb.append(binaryOP.operator); sb.append(binaryOP.rightExpression.accept(this)); } - + //adds right bracket if the BinaryOperation is capsuled if(binaryOP.capsuled) { sb.append(")"); } return sb.toString(); } + + /** + * Returns the result of ast.accept(this), which will be the core values of a Value(digits), + * Variable(variableName) or BinaryOperation(will lead to a recursive call) + * @param ast The Expression + * @return ast.accept(this) + */ + public String visit(final Parser.Expression ast) { + if(ast==null) { + throw new RuntimeException("AST is null"); + } + return ast.accept(this); + } + + /** + * @see #visit(Parser.Expression) + */ @Override public String visit(Parser.Variable variable) { return variable.variableName; } + /** + * @see #visit(Parser.Expression) + */ @Override public String visit(Parser.Number number) { return number.digits; } + /** + * @see #visit(Parser.Expression) + */ @Override public String visit(Parser.Decimal decimal) { return decimal.beforeDot.digits + "." + decimal.afterDot.digits; } - - public String visit(final Parser.Expression ast) { - if(ast==null) { - throw new RuntimeException("AST is null"); - } - return ast.accept(this); - } }