bakpakin / Fennel

Lua Lisp Language
https://fennel-lang.org
MIT License
2.42k stars 124 forks source link

macro question: access a function's form inside a macro #472

Closed brenopacheco closed 5 months ago

brenopacheco commented 7 months ago

Is it possible to access a function's form inside a macro?

Is it possible to write a macro that re-defines a function, using it's original form. For example:

(fn my-fun [x] (+ 1 x))

(macro modify-fun [f] ;; ...

(modify-fun my-fun) ;; => (fn my-fun [x] (+ 1 (+ 1 x)))

I'm also not entirely sure if the compiler context is able to access my-fun even if I attach it to _G, even using --no-compiler-sandbox

technomancy commented 7 months ago

In theory it could be possible to make this work in trivial cases where the function is defined in the same file, but there's no way this could work for the general case. The function might not even be written in Fennel to begin with, or it could be defined in the repl, or any other number of things that can't be determined at compile time.

The compiler sandbox isn't really relevant here; the function wouldn't be created till runtime after the macro had finished running. (Even if that weren't true, that would be the function value, not the form.)