ref(ClavaLaraApi): Refactor pass SimplifyLoops
- Apply to all loops queriable from jp
- Factor the different logical steps
@@ -3,6 +3,7 @@ laraImport("clava.ClavaJoinPoints");
laraImport("clava.code.StatementDecomposer");
laraImport("clava.code.ForToWhileStmt");
laraImport("clava.code.DoToWhileStmt");
+laraImport("weaver.Query");
class SimplifyLoops extends Pass {
#statementDecomposer;
@@ -13,48 +14,55 @@ class SimplifyLoops extends Pass {
}
_apply_impl($jp) {
- if (
- $jp.instanceOf("loop") &&
- ($jp.kind === "for" || $jp.kind === "dowhile")
- ) {
- let $currentNode = $jp;
- if ($jp.kind === "for") {
- const $forToWhileScope = ForToWhileStmt($jp);
+ let appliedPass = false;
+ for (const $loop of this.#findLoops($jp)) {
+ appliedPass = true;
+ const $whileLoop = this.#makeWhileLoop($loop);
+ this.#transform($whileLoop);
+ }
+
+ return new PassResult(this.name, {
+ appliedPass,
+ insertedLiteralCode: false,
+ location: $jp.location,
+ });
+ }
+
+ #findLoops($jp) {
+ return Query.searchFromInclusive($jp, "loop", {
+ kind: (kind) => kind === "for" || kind === "dowhile" || kind === "while",
+ });
+ }
+
+ #makeWhileLoop($loop) {
+ if ($loop.kind === "for") {
+ const $forToWhileScope = ForToWhileStmt($loop);
const [_, $while] = $forToWhileScope.children;
- $currentNode = $while;
- } else if ($jp.kind === "dowhile") {
- $currentNode = DoToWhileStmt($jp);
+ return $while;
+ } else if ($loop.kind === "dowhile") {
+ return DoToWhileStmt($loop);
+ } else {
+ return $loop;
+ }
}
- const $loopCond = $currentNode.cond;
+ #transform($whileLoop) {
+ const $loopCond = $whileLoop.cond;
const decomposeResult = this.#statementDecomposer.decomposeExpr(
$loopCond.expr
);
for (const stmt of decomposeResult.precedingStmts) {
- $currentNode.insertBefore(stmt);
+ $whileLoop.insertBefore(stmt);
}
for (const stmt of decomposeResult.succeedingStmts) {
- $currentNode.insertAfter(stmt);
+ $whileLoop.insertAfter(stmt);
}
for (const stmt of decomposeResult.succeedingStmts.slice().reverse()) {
- $currentNode.body.insertBegin(stmt);
+ $whileLoop.body.insertBegin(stmt);
}
- $currentNode.cond.replaceWith(
+ $whileLoop.cond.replaceWith(
ClavaJoinPoints.exprStmt(decomposeResult.$resultExpr)
);
-
- return new PassResult(this.name, {
- appliedPass: true,
- insertedLiteralCode: false,
- location: $jp.location,
- });
- }
-
- return new PassResult(this.name, {
- appliedPass: false,
- insertedLiteralCode: false,
- location: $jp.location,
- });
}
}
