Skip to content
Snippets Groups Projects
Commit f4eda906 authored by Dominic Daniel Krämer's avatar Dominic Daniel Krämer
Browse files

implemented ASTPrinter to test the visitor pattern

parent 9a8c6438
No related branches found
No related tags found
1 merge request!10Dominicsbranch
1 + xy^2 - (31 * x)y 1 + x*y^2 - (31 * x)-y
1 + x^2 - (3 * x) 1 + x^2 - (3 * x)
2x + 0.5x^2 - 1 2-x + 0.5*x^2 - 1
((5+2)-8)-8+12
(5*2-(5^2)+3*(201.01-15)) (5*2-(5^2)+3*(201.01-15))
\ No newline at end of file
public class ASTPrinter implements Visitor<String>{
@Override
public String visit(final Parser.BinaryOperation binaryOP) {
StringBuffer sb = new StringBuffer();
if(binaryOP.capsuled) {
sb.append("(");
}
sb.append(binaryOP.leftExpression.accept(this));
sb.append(binaryOP.operator);
sb.append(binaryOP.rightExpression.accept(this));
if(binaryOP.capsuled) {
sb.append(")");
}
return sb.toString();
}
@Override
public String visit(Parser.Variable variable) {
return variable.variableName;
}
@Override
public String visit(Parser.Number number) {
return number.digits;
}
@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);
}
}
...@@ -40,7 +40,8 @@ public class Application { ...@@ -40,7 +40,8 @@ public class Application {
Parser parser = new Parser(); Parser parser = new Parser();
try { try {
Parser.Expression exp = parser.parse(tokens); Parser.Expression exp = parser.parse(tokens);
System.out.println(exp.toString()); ASTPrinter printer = new ASTPrinter();
System.out.println("Printing: '" + printer.visit(exp) + "'");
} }
catch (ParserException e) { catch (ParserException e) {
System.out.println(e.getMessage()); System.out.println(e.getMessage());
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment