我正在用 Java 编写一个 AST 解释器,它有很多方法可以检查参数类型并在它们匹配时执行操作。到目前为止,已经有五种以上的方法,它们基本上是相互复制粘贴的版本。有没有办法抽象要检查的类型和要执行的操作?
@Override
public Object visitMultiplyNode(MultiplyNode multiplyNode) {
Object lhs = multiplyNode.getLeftHandSide().accept(this);
Object rhs = multiplyNode.getRightHandSide().accept(this);
if (lhs instanceof Double && rhs instanceof Double) {
return (double) lhs * (double) rhs;
}
if (lhs instanceof Long && rhs instanceof Long) {
return (long) lhs * (long) rhs;
}
throw new TypeError("Can not multiply " + lhs.getClass() + " and " + rhs.getClass() + ".");
}
我要检查的类型并不总是相同的,例如,模数节点只接受 Longs 而加法节点也接受 Strings 进行连接。
@Override
public Object visitAddNode(AddNode addNode) {
Object lhs = addNode.getLeftHandSide().accept(this);
Object rhs = addNode.getRightHandSide().accept(this);
if (lhs instanceof Double && rhs instanceof Double) {
return (double) lhs + (double) rhs;
}
if (lhs instanceof Long && rhs instanceof Long) {
return (long) lhs + (long) rhs;
}
if (lhs instanceof String && rhs instanceof String) {
return "" + lhs + lhs;
}
throw new TypeError("Can not add " + lhs.getClass() + " and " + rhs.getClass() + ".");
}
@Override
public Object visitModulusNode(ModulusNode modulusNode) {
Object lhs = modulusNode.getLeftHandSide().accept(this);
Object rhs = modulusNode.getRightHandSide().accept(this);
if (lhs instanceof Long && rhs instanceof Long) {
return (long) lhs % (long) rhs;
}
throw new TypeError("Can not take modulus of " + lhs.getClass() + " and " + rhs.getClass() + ".");
}
慕运维8079593
慕的地8271018
相关分类