egraphs-good / egglog

egraphs + datalog!
https://egraphs-good.github.io/egglog/
MIT License
400 stars 45 forks source link

Support for macros to reduce code duplication #356

Open segeljakt opened 5 months ago

segeljakt commented 5 months ago

Hi, currently when using egglog there is some code duplication in my programs. For example:

(push)
;; 2 * (x + 3) = 6 + 2 * x
(let a0 (Mul (I64 2) (Add (Var "x") (I64 3))))
(let b0 (Add (I64 6) (Mul (I64 2) (Var "x"))))

(run-schedule
  (seq
    (run desugar)
    (saturate (run arith))))
(check (= a1 b1))
(pop)

(push)
;; 6 + 2 * 3 = 12
(let a1 (Add (I64 6) (Mul (I64 2) (I64 3))))
(let b1 (I64 12))

(run-schedule
  (seq
    (run desugar)
    (saturate (run arith))))
(check (= a0 b0))
(pop)

If I am not missing something, it is currently not possible to parameterise commands/expressions. The only workaround I see is to write a program in Rust/Python which calls into Egglog.

Would it be possible to add basic support for macros that rely on textual substitution in egglog? This would allow reusing commands such as:

; Define a macro which takes 2 parameters e0 and e1
(macro test (e0 e1)
  ((push)
   (let a e0)
   (let b e1)

   (run-schedule
     (seq
       (run desugar)
       (saturate
         (run-schedule
           (seq
             (run desugar)
             (saturate (run arith))))
   (check (= a b))
   (pop)))

; Use the macros
(call-macro test
  ((Mul (I64 2) (Add (Var "x") (I64 3)))
   (Add (I64 6) (Mul (I64 2) (Var "x")))))

(call-macro test
  ((Add (I64 6) (Mul (I64 2) (I64 3)))
   (I64 12)))
oflatt commented 5 months ago

I agree that macros would be quite useful in egglog. However, text-based macros are usually a terrible source of bugs. A more promising direction would be to re-use an existing macro system, such as rust's or racket's. A #lang egglog would work well This is related to #232

segeljakt commented 5 months ago

Hmm, I haven't tried Racket but it looks like a good fit. I think there is also a lot of potential in making Egglog more powerful on its own, but maybe this is not important if Egglog is aimed to be a target for code generation.

oflatt commented 5 months ago

Yeah, I think egglog as a target vs a language is up in the air right now