From 12a0f17e59c4a8c3612ee0f67d79f04d1934fb56 Mon Sep 17 00:00:00 2001 From: Graham Date: Tue, 4 Aug 2020 14:16:30 +0100 Subject: [PATCH] Replace ternaries in an else block with another if/else Signed-off-by: Graham --- .../deob/ast/transform/IfElseTransformer.kt | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/deob-ast/src/main/java/dev/openrs2/deob/ast/transform/IfElseTransformer.kt b/deob-ast/src/main/java/dev/openrs2/deob/ast/transform/IfElseTransformer.kt index 2d185a72..2240630a 100644 --- a/deob-ast/src/main/java/dev/openrs2/deob/ast/transform/IfElseTransformer.kt +++ b/deob-ast/src/main/java/dev/openrs2/deob/ast/transform/IfElseTransformer.kt @@ -1,8 +1,11 @@ package dev.openrs2.deob.ast.transform import com.github.javaparser.ast.CompilationUnit +import com.github.javaparser.ast.NodeList +import com.github.javaparser.ast.expr.ConditionalExpr import com.github.javaparser.ast.stmt.BlockStmt import com.github.javaparser.ast.stmt.IfStmt +import com.github.javaparser.ast.stmt.ReturnStmt import com.github.javaparser.ast.stmt.Statement import dev.openrs2.deob.ast.Library import dev.openrs2.deob.ast.LibraryGroup @@ -167,6 +170,46 @@ class IfElseTransformer : Transformer() { elseStmt.replace(IfStmt(condition, tail, thenStmt.clone())) } } + + /** + * Rewrite: + * + * } else { + * return a ? ... : ...; + * } + * + * to: + * + * } else if (a) { + * return ...; + * } else { + * return ...; + * } + */ + unit.walk { stmt: IfStmt -> + stmt.elseStmt.ifPresent { elseStmt -> + // match + if (elseStmt !is BlockStmt) { + return@ifPresent + } + + val head = elseStmt.statements.singleOrNull() ?: return@ifPresent + if (head !is ReturnStmt) { + return@ifPresent + } + + head.expression.ifPresent { expr -> + if (expr !is ConditionalExpr) { + return@ifPresent + } + + // replace + val thenBlock = BlockStmt(NodeList(ReturnStmt(expr.thenExpr))) + val elseBlock = BlockStmt(NodeList(ReturnStmt(expr.elseExpr))) + stmt.setElseStmt(IfStmt(expr.condition, thenBlock, elseBlock)) + } + } + } } private fun Statement.isIf(): Boolean {