|
| 1 | +from kirin import ir |
| 2 | +from kirin.analysis import const |
| 3 | +from kirin.rewrite.abc import RewriteRule |
| 4 | +from kirin.rewrite.result import RewriteResult |
| 5 | +from kirin.dialects.py.constant import Constant |
| 6 | + |
| 7 | +from .stmts import For, Yield |
| 8 | + |
| 9 | + |
| 10 | +class ForLoop(RewriteRule): |
| 11 | + |
| 12 | + def rewrite_Statement(self, node: ir.Statement) -> RewriteResult: |
| 13 | + if not isinstance(node, For): |
| 14 | + return RewriteResult() |
| 15 | + |
| 16 | + # TODO: support for PartialTuple and IList with known length |
| 17 | + if not isinstance(hint := node.iterable.hints.get("const"), const.Value): |
| 18 | + return RewriteResult() |
| 19 | + |
| 20 | + loop_vars = node.initializers |
| 21 | + for item in hint.data: |
| 22 | + body = node.body.clone() |
| 23 | + block = body.blocks[0] |
| 24 | + item_stmt = Constant(item) |
| 25 | + item_stmt.insert_before(node) |
| 26 | + block.args[0].replace_by(item_stmt.result) |
| 27 | + for var, input in zip(block.args[1:], loop_vars): |
| 28 | + var.replace_by(input) |
| 29 | + |
| 30 | + block_stmt = block.first_stmt |
| 31 | + while block_stmt and not block_stmt.has_trait(ir.IsTerminator): |
| 32 | + block_stmt.detach() |
| 33 | + block_stmt.insert_before(node) |
| 34 | + block_stmt = block.first_stmt |
| 35 | + |
| 36 | + terminator = block.last_stmt |
| 37 | + # we assume Yield has the same # of values as initializers |
| 38 | + # TODO: check this in validation |
| 39 | + if isinstance(terminator, Yield): |
| 40 | + loop_vars = terminator.values |
| 41 | + |
| 42 | + for result, output in zip(node.results, loop_vars): |
| 43 | + result.replace_by(output) |
| 44 | + node.delete() |
| 45 | + return RewriteResult(has_done_something=True) |
0 commit comments