Skip to content

Add method for extracting terms that match a pattern in python #360

@goombamaui

Description

@goombamaui

I am using egglog to implement a few compiler simplification rules and one thing I want to do is use extraction based substitution. As a simplified example, if I have Expression.Let("x", 3, exp2) which corresponds to let x=3 in exp2, I could use egglog rules to simplify this using rewrites: rewrite(Expression.Let(vname, Expression.Int(ival), exp2)).to(...), but I want to instead defer this to a python function (IE: rule(e1 == <something>).then(union(e1).with_(f(e1))) where f is a python function). Essentially, I want to be able to have a rule rule(e1==<something>) and be able to passed the matched expression e1 (rebuilt in python) into a python function (and use methods like get_callable_args, etc. on it).

However, I do not think this can be done currently; py_eval_fn and PyObject.from_string work when trying to have a rule execute a python function that depends on string (or other primitive) values in the matched expression:

from egglog import *

class A(Expr):
    def __init__(self, v:StringLike): ...
def say_hi(x: String):
    print("Hi, " + str(x))

egraph = EGraph()

expr = egraph.let("expr", A("x"))
svar = var("svar", String)
avar = var("avar", A)
egraph.register(rule(avar==A(svar)).then(py_eval_fn(say_hi)(PyObject.from_string(svar))))
print("Starting")
egraph.run(1)

However, replacing PyObject.from_string(svar) with PyObject(avar) and modifying say_hi to use the matched object seems to fail. Perhaps one potential solution would be to have a PyObject.from_expr that translates a variable from its egraph representation back into python.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions