|
| 1 | +from textwrap import dedent |
| 2 | + |
| 3 | +from .finch_logic import Alias, Deferred, Field, Immediate, LogicNode, MapJoin, Query, Reformat, Relabel, Reorder, Table |
| 4 | + |
| 5 | + |
| 6 | +class PointwiseLowerer: |
| 7 | + def __init__(self): |
| 8 | + self.bound_idxs = [] |
| 9 | + |
| 10 | + def __call__(self, ex): |
| 11 | + match ex: |
| 12 | + case MapJoin(op, args) if isinstance(op, Immediate): |
| 13 | + return f":({op.val}({','.join([self(arg) for arg in args])}))" |
| 14 | + case Reorder(Relabel(arg, idxs_1), idxs_2) if isinstance(arg, Alias): |
| 15 | + self.bound_idxs.append(idxs_1) |
| 16 | + return f":({arg.name}[{','.join([idx.name if idx in idxs_2 else 1 for idx in idxs_1])}])" |
| 17 | + case Reorder(arg, _) if isinstance(arg, Immediate): |
| 18 | + return arg.val |
| 19 | + case Immediate(val): |
| 20 | + return val |
| 21 | + case _: |
| 22 | + raise Exception(f"Unrecognized logic: {ex}") |
| 23 | + |
| 24 | + |
| 25 | +def compile_pointwise_logic(ex: LogicNode) -> tuple: |
| 26 | + ctx = PointwiseLowerer() |
| 27 | + code = ctx(ex) |
| 28 | + return (code, ctx.bound_idxs) |
| 29 | + |
| 30 | + |
| 31 | +def compile_logic_constant(ex): |
| 32 | + match ex: |
| 33 | + case Immediate(val): |
| 34 | + return val |
| 35 | + case Deferred(ex, type_): |
| 36 | + return f":({ex}::{type_})" |
| 37 | + case _: |
| 38 | + raise Exception(f"Invalid constant: {ex}") |
| 39 | + |
| 40 | + |
| 41 | +class LogicLowerer: |
| 42 | + def __init__(self, mode: str = "fast"): |
| 43 | + self.mode = mode |
| 44 | + |
| 45 | + def __call__(self, ex): |
| 46 | + match ex: |
| 47 | + case Query(lhs, Table(tns, _)) if isinstance(lhs, Alias): |
| 48 | + return f":({lhs.name} = {compile_logic_constant(tns)})" |
| 49 | + |
| 50 | + case Query(lhs, Reformat(tns, Reorder(Relabel(arg, idxs_1), idxs_2))) if isinstance( |
| 51 | + lhs, Alias |
| 52 | + ) and isinstance(arg, Alias): |
| 53 | + loop_idxs = [idx.name for idx in withsubsequence(intersect(idxs_1, idxs_2), idxs_2)] # noqa: F821 |
| 54 | + lhs_idxs = [idx.name for idx in idxs_2] |
| 55 | + (rhs, rhs_idxs) = compile_pointwise_logic(Reorder(Relabel(arg, idxs_1), idxs_2)) |
| 56 | + body = f":({lhs.name}[{','.join(lhs_idxs)}] = {rhs})" |
| 57 | + for idx in loop_idxs: |
| 58 | + if Field(idx) in rhs_idxs: |
| 59 | + body = f":(for {idx} = _ \n {body} end)" |
| 60 | + elif idx in lhs_idxs: |
| 61 | + body = f":(for {idx} = 1:1 \n {body} end)" |
| 62 | + |
| 63 | + result = f"""\ |
| 64 | + quote |
| 65 | + {lhs.name} = {compile_logic_constant(tns)} |
| 66 | + @finch mode = {self.mode} begin |
| 67 | + {lhs.name} .= {tns.fill_value} |
| 68 | + {body} |
| 69 | + return {lhs.name} |
| 70 | + end |
| 71 | + end |
| 72 | + """ |
| 73 | + return dedent(result) |
| 74 | + |
| 75 | + |
| 76 | +class LogicCompiler: |
| 77 | + def __call__(self, prgm): |
| 78 | + prgm = format_queries(prgm, True) # noqa: F821 |
| 79 | + return LogicLowerer()(prgm) |
0 commit comments