Improve Expression.negate()

This commit makes two changes:

* Uses the is operator instead of the isXXX methods provided by
  JavaParser, allowing smart casts to be used.
* Wraps unsupported expressions with a unary minus expression, rather
  than throwing an exception.

Signed-off-by: Graham <gpe@openrs2.dev>
Graham 4 years ago
parent e0708458f9
commit d33c03c708
  1. 17
      deob-ast/src/main/java/dev/openrs2/deob/ast/util/ExprUtils.kt

@ -32,22 +32,23 @@ fun Long.toLongLiteralExpr(): LongLiteralExpr {
}
fun Expression.negate(): Expression {
return if (isUnaryExpr && asUnaryExpr().operator == UnaryExpr.Operator.MINUS) {
asUnaryExpr().expression.clone()
} else if (isIntegerLiteralExpr) {
when (val n = asIntegerLiteralExpr().asNumber()) {
return when (this) {
is UnaryExpr -> when (operator) {
UnaryExpr.Operator.PLUS -> UnaryExpr(expression.clone(), UnaryExpr.Operator.MINUS)
UnaryExpr.Operator.MINUS -> expression.clone()
else -> UnaryExpr(clone(), UnaryExpr.Operator.MINUS)
}
is IntegerLiteralExpr -> when (val n = asNumber()) {
IntegerLiteralExpr.MAX_31_BIT_UNSIGNED_VALUE_AS_LONG -> IntegerLiteralExpr(Integer.MIN_VALUE.toString())
is Int -> IntegerLiteralExpr((-n.toInt()).toString())
else -> error("Invalid IntegerLiteralExpr type")
}
} else if (isLongLiteralExpr) {
when (val n = asLongLiteralExpr().asNumber()) {
is LongLiteralExpr -> when (val n = asNumber()) {
LongLiteralExpr.MAX_63_BIT_UNSIGNED_VALUE_AS_BIG_INTEGER -> Long.MIN_VALUE.toLongLiteralExpr()
is Long -> (-n).toLongLiteralExpr()
else -> error("Invalid LongLiteralExpr type")
}
} else {
throw IllegalArgumentException()
else -> UnaryExpr(clone(), UnaryExpr.Operator.MINUS)
}
}

Loading…
Cancel
Save