I finished converting the ANTLR CST into an AST and created a specific Visitor<T> interface that allows me to visit all my AST nodes, but the main issue i'm having is that some visits should return different data types, and i'm not sure how to go about this.
For example, for simple arithmetics operations i want to return a double from their respective visit methods; but other string operation would require their respective nodes to return a string.
Since my visit methods all require a generic type T, I tried making a class called Result and two child classes DoubleResult and StringResult so that my visitor can return either a string or double during visits but it seems bad and full of cast and type checks.
Is there a better way to do things like this ?
Here's an example code :
public class ExpressionVisitor implements Visitor<Result> {
...
public Result visit(BinaryExpression node) {
// here the node's left or right can be StringResults
// So i'd have to do instance and type checks
}
public Result visit(StringExpression node) {
// here i'd return a StringResult specifically
}
}
Edit:
The goal is to be able to do string arithmetics for example like in python for instance 2*"hello"
But then the binary expression visit method would have to check for which operand is a string (left or right), and then most of the other visit methods would need to check and handle either a DoubleResult or StringResult type accordingly. Is there a cleaner way of achieving the same thing ?