IllegalStateException: Attempting to call unbound fn in macro - macros

I'm trying to write a macro that calls some functions. The functions should only be used by the macro, so I put them inside of a letfn wrapping the macro. Pseudocode:
(letfn [(fn-a [] ...)
(fn-b [] ...)
(fn-c [] (fn-b))]
(defmacro my-macro [stuff]
`(let [whatever# (fn-a)]
(fn-c))))
The calls to fn-a and fn-c work, but when fn-c tries to call fn-b I get IllegalStateException: Attempting to call unbound fn: #'name.space/fn-b. Why is that?
If I put fn-b and fn-c in their own defns, everything works. But I don't want to do that because it isn't clean.
Edit: Just to test, I tried putting the function bindings in the inner let but ran into the same exception.

I don't think this can work at all this way.
The call to fn-c for example gets expanded to your.namespace/fn-c, so your code seems to call other functions that just happen to have the same names.
But you dont have a your.namespace/fn-b, which raises the exception.
To refer to a unqualified symbol you need to quote and unquote it: ~'fn-a
But this won't work either because the local functions aren't defined at the point of expansion, you can only use them for the macro itself.
You either have to define the functions in a namespace and qualify them in the macro or include them in the macroexpansion, which would define them again at each use.

I'm not sure if this is exactly what you're after but if I do:
(letfn [(fn-a [] (println 1))
(fn-b [] (println 2))
(fn-c [] (fn-b))]
(defmacro my-macro [stuff]
`(let [whatever# ~(fn-b)]
~(fn-c))))
then it works - it just needs the tilde to unquote the function calls.
Both of the following work:
(defn fn-x [] (println 1))
(defn fn-y [] (fn-x))
(defmacro my-macro2 [stuff]
`(let [whatever# (fn-x)]
(fn-y)))
AND
(defn fn-x [] (println 1))
(defn fn-y [] (fn-x))
(defmacro my-macro2 [stuff]
`(let [whatever# ~(fn-x)]
~(fn-y)))
In the first case, the functions are being evaluated and their results incorporated into the macro at compile time whereas in the second they are being evaluated at runtime. With the letfn (which is a macro itself) the results are not available at compile time (presumably because they are being compiled after your macro is compiled) so the functions can only be used at runtime.

Related

Clojure: Defining a Macro that Uses the Carret (^{}) Metadata Syntax

I am trying to define a macro like this:
(defmacro foo-macro
"[name] is the name of the function to define
[meta-data] is the map that defines the meta-data of the function"
[name meta-data]
(let [vals (gensym "label-")]
`(def ~name
^#~meta-data
(fn [~vals] (eval nil)))))
However, I am getting this compilation error:
Unhandled java.lang.IllegalArgumentException Metadata must be
Symbol,Keyword,String or Map
I think this is normal. However, I am not sure how I can make such a macro to work, or if it is even possible.
Note: I do not want to use with-meta. Read the revision of the resolution of this other question to understand why: Clojure: issues getting the symbol of a function in a looping context.
The only reason why I would use with-meta, is if you have a way to make it return a non-AFunc identifier.
I'm sorry, but you do want to use with-meta, you just want to use it within your macro rather than within the code you return.
The form that you get by reading ^{:foo :bar} (fn []) is approximately the same as what you get by evaluating (with-meta `(fn [])), so that's what you want to do in your macro: evaluate the with-meta call while generating code.
(defmacro foo-macro
"[name] is the name of the function to define
[meta-data] is the map that defines the meta-data of the function"
[name meta-data]
(let [vals (gensym "label-")]
`(def ~name
~(with-meta `(fn [~vals] (eval nil))
meta-data))))
Calling (foo-macro fn-name {:foo "bar"}) should give you what you want: a function with (meta fn-name) returning {:foo "bar"} which, when printed, comes out something like #<user$fn_name user$fn_name#35df85a1>.

Local context in a literal tag

Can literal tags capture local context bindings, so for instance if i have a tag #my/closuretag whose reader function is closuretag
(defrecord MyRecord [f])
(defn closuretag [f] (MyRecord. (eval f)))
For above defintions, #my/closuretag inc would work fine but
(let [foo 1] #my/closuretag #(inc foo)) would fail.
Can a literal tag be made to work for this case? May be by a macro instead of a plain reader function?
Edit:
Here is something weird, If i change closuretag function to (defn closuretag [f] f), I get a proper closure with scoped variables bound inside the function which is callable! Why does using record here causing f to be a list of symbols?!
I am guessing that we should infer from literal tag vs. tagged element and the behavior described in your edit, that you are referring to readers installed in data_readers.clj, and not readers for data through (edn/) read or read-string.
Since these are reader functions, they are going to behave like macros in that you can conceptually consider the arguments to be quoted and results evaluated as code.
So, you want this
(defrecord MyRecord [f])
(defn my-tag-reader [f] (list ->MyRecord f))
To get the behavior of this
(def my-record (let [foo 1] #my/example-tag #(inc foo)))
((:f my-record)) ;=> 2
When my-tag-reader is the (namespaced qualified) reader function of #my/example-tag in the data_readers.clj map.

Can I get rid of these eval?

I'd like to build a list of operations to execute in a Redis pipeline. I was using accession since it's much simpler than carmine, but now I need connection pooling (missing from accession) and thus I'm looking at carmine again (it seems the go-to and most complete clojure library for redis)
I managed to get this working:
; require [taoensso.carmine :as redis]
(defn execute1 [request] (redis/wcar {} (eval request)))
(defmacro execute [body] `(redis/wcar {} ~#(eval body)))
(def get1 `(redis/get 1))
(execute1 get1)
(execute [get1])
but given that I'll build vectors of thousands of elements, I'm a bit worried about the possible performance hit of eval (besides the fact that I've been taught to always avoid eval if possible). I reckon that defmacro instead is/can be evaluated at macro-expansion time, which might be earlier (during AOT compilation?) and without using eval.
Is there anything that I can do? should I move to a different library?
(I had a look at carmine's source code: my pain is only due to a small convenience for the author: a *context* used to avoid passing around a couple extra argument: getting rid of it should be simple enough, but I'm not invested enough in it... I might as well decide to move to another data store in the future)
edit: I've been asked to write an example of what I think is the boilerplate that I'd prefer to avoid writing in my actual code, so: (the following is untested, it's just a POC)
(defn hset [id key val]
#(redis/hset id key val))
(defn hsetnx [id key val]
#(redis/hsetnx id key val))
(defn hincrby [id key increment]
#(redis/hincrby id key increment))
(defn hgetall [id key]
#(redis/hgetall id key))
(defn sadd [id el]
#(redis/sadd id el))
(defn scard [id]
#(redis/scard id))
(defn smembers [id]
#(redis/smembers id))
(defmacro execute [forms]
`(redis/wcar {} ~#(map apply forms)))
; end boilerplate
(defn munge-element [[a b c]]
(conj
(mapcat #(hincrby a :whatever %) b)
(sadd c b)
(hsetnx a c))
(defn flush-queue! [queue_]
(execute queue_)
[])
(defn receive [item]
(if (< (count #queue) 2000)
(swap! queue conj (munge-element item))
(swap! queue flush-queue!)))
Obviously, I could write something like this, but if this was truly the inteneded way to use carmine, these curried functions would be provided along (or instead of) the normal ones. Also a lot of lines could be shaved off by constructing up the defs with syntax quoting, but this is accidental complexity, not inherent the original problem.
The following piece of code does not differ very much from yours:
(defmacro execute [& forms]
`(redis/wcar {} ~#forms))
(defn get1 []
(redis/get 1))
(execute (get1) (get1) ...)
This is basically how carmine should be used (following this suggestion in the README). If it doesn't suit your needs, could you clarify why?
After the question was edited to present more clearly what should be accomplished I think I have a solution for you. You're trying to create a list of statements to be executed at some specific time in the future. To achieve this you're wrapping each statement inside a function and I agree, that's a lot of boilerplate.
But unnecessary. You can get the same result by having a macro that automatically creates thunks for you:
(defmacro statements [& forms]
`(vector
~#(for [f forms]
`(fn [] ~f))))
Now, whatever you pass to this macro will result in a vector of zero-parameter functions that can be evaluated e.g. using:
(defn execute-statements [fns]
(redis/wcar {} (mapv #(%) fns))
And your example turns into something along the lines of:
(defn munge-element [[a b c]]
(statements
(mapcat #(redis/hincrby a :whatever %) b)
(redis/sadd c b)
(redis/hsetnx a c))
(defn flush-queue! [queue_]
(mapv execute-statements queue_)
[])
Edit: This executes every batch in its own pipeline. If you want to do it in a single one, use concat instead of conj to build up your queue (in receive) and (execute-statements queue_) instead of (mapv execute-statements queue_).
Note: IIRC correctly, this:
(redis/wcar {} a [b c]])
returns the same result as this:
(redis/wcar {} a b c)
I.e., carmine collects the results somewhere and always returns a vector for all of them. Even if not, I think you can still avoid your dreaded boilerplate by just tweaking the stuff presented here a little bit.

Dynamic scope in macros

Is there a clean way of implementing dynamic scope that will "reach" into macro calls? Perhaps more importantly, even if there is, should it be avoided?
Here's what I'm seeing in a REPL:
user> (def ^:dynamic *a* nil)
> #'user/*a*
user> (defn f-get-a [] *a*)
> #'user/f-get-a
user> (defmacro m-get-a [] *a*)
> #'user/m-get-a
user> (binding [*a* "boop"] (f-get-a))
> "boop"
user> (binding [*a* "boop"] (m-get-a))
> nil
This m-get-a macro isn't my actual goal, it's just a boiled down version of the problem I have been running into. It took me a while to realize, though, because I kept debugging with macroexpand, which makes everything seem fine:
user> (binding [*a* "boop"] (macroexpand '(m-get-a)))
> "boop"
Doing macroexpand-all (used from clojure.walk) on the outer binding call leads me to believe that the "issue" (or feature, as the case may be) is that (m-get-a) is getting evaluated before the dynamic binding takes:
user> (macroexpand-all '(binding [*a* "boop"] (f-get-a)))
> (let* []
(clojure.core/push-thread-bindings (clojure.core/hash-map #'*a* "boop"))
(try (f-get-a) (finally (clojure.core/pop-thread-bindings))))
user> (macroexpand-all '(binding [*a* "boop"] (m-get-a)))
> (let* []
(clojure.core/push-thread-bindings (clojure.core/hash-map #'*a* "boop"))
(try nil (finally (clojure.core/pop-thread-bindings))))
Here's my crack at a workaround:
(defmacro macro-binding
[binding-vec expr]
(let [binding-map (reduce (fn [m [symb value]]
(assoc m (resolve symb) value))
{}
(partition 2 binding-vec))]
(push-thread-bindings binding-map)
(try (macroexpand expr)
(finally (pop-thread-bindings)))))
It will evaluate a single macro expression with the relevant dynamic bindings. But I don't like using macroexpand in a macro, that just seems wrong. It also seems wrong to resolve symbols in a macro--it feels like a half-assed eval.
Ultimately, I'm writing a relatively lightweight interpreter for a "language" called qgame, and I'd like the ability to define some dynamic rendering function outside of the context of the interpreter execution stuff. The rendering function can perform some visualization of sequential instruction calls and intermediate states. I was using macros to handle the interpreter execution stuff. As of now, I've actually switched to using no macros at all, and also I have the renderer function as an argument to my execution function. It honestly seems way simpler that way, anyways.
But I'm still curious. Is this an intended feature of Clojure, that macros don't have access to dynamic bindings? Is it possible to work around it anyways (without resorting to dark magic)? What are the risks of doing so?
Macro expansion take place during the compilation of you program, so it's imposisble to predict the future value of dynamic variable at that time.
But, probably, you don't need to evaluate *a* during macro expansion and just wants to leave it as is. It this case *a* will be evaluated when the actual code is called. In this case you should quote it with ` symbol:
(defmacro m-get-a [] `*a*)
Your implementation of m-get-a causes clojure to replace (m-get-a) with its value when the code is compiled, which is the core binding of *a*, while my wersion causes it to replace (m-get-a) with variable *a* itself.
You need to quote *a* to make it work:
user=> (def ^:dynamic *a* nil)
#'user/*a*
user=> (defmacro m-get-a [] `*a*)
#'user/m-get-a
user=> (binding [*a* "boop"] (m-get-a))
"boop"

Use a clojure macro to automatically create getters and setters inside a reify call

I am trying to implement a huge Java interface with numerous (~50) getter and setter methods (some with irregular names). I thought it would be nice to use a macro to reduce the amount of code. So instead of
(def data (atom {:x nil}))
(reify HugeInterface
(getX [this] (:x #data))
(setX [this v] (swap! data assoc :x v)))
I want to be able to write
(def data (atom {:x nil}))
(reify HugeInterface
(set-and-get getX setX :x))
Is this set-and-get macro (or something similar) possible? I haven't been able to make it work.
(Updated with a second approach -- see below the second horizontal rule -- as well as some explanatory remarks re: the first one.)
I wonder if this might be a step in the right direction:
(defmacro reify-from-maps [iface implicits-map emit-map & ms]
`(reify ~iface
~#(apply concat
(for [[mname & args :as m] ms]
(if-let [emit ((keyword mname) emit-map)]
(apply emit implicits-map args)
[m])))))
(def emit-atom-g&ss
{:set-and-get (fn [implicits-map gname sname k]
[`(~gname [~'this] (~k #~(:atom-name implicits-map)))
`(~sname [~'this ~'v]
(swap! ~(:atom-name implicits-map) assoc ~k ~'v))])})
(defmacro atom-bean [iface a & ms]
`(reify-from-maps ~iface {:atom-name ~a} ~emit-atom-g&ss ~#ms))
NB. that the atom-bean macro passes the actual compile-time value of emit-atom-g&ss on to reify-from-maps. Once a particular atom-bean form is compiled, any subsequent changes to emit-atom-g&ss have no effect on the behaviour of the created object.
An example macroexpansion from the REPL (with some line breaks and indentation added for clarity):
user> (-> '(atom-bean HugeInterface data
(set-and-get setX getX :x))
macroexpand-1
macroexpand-1)
(clojure.core/reify HugeInterface
(setX [this] (:x (clojure.core/deref data)))
(getX [this v] (clojure.core/swap! data clojure.core/assoc :x v)))
Two macroexpand-1s are necessary, because atom-bean is a macro which expands to a further macro call. macroexpand would not be particularly useful, as it would expand this all the way to a call to reify*, the implementation detail behind reify.
The idea here is that you can supply an emit-map like emit-atom-g&ss above, keyed by keywords whose names (in symbolic form) will trigger magic method generation in reify-from-maps calls. The magic is performed by the functions stored as functions in the given emit-map; the arguments to the functions are a map of "implicits" (basically any and all information which should be accessible to all method definitions in a reify-from-maps form, like the name of the atom in this particular case) followed by whichever arguments were given to the "magic method specifier" in the reify-from-maps form. As mentioned above, reify-from-maps needs to see an actual keyword -> function map, not its symbolic name; so, it's only really usable with literal maps, inside other macros or with help of eval.
Normal method definitions can still be included and will be treated as in a regular reify form, provided keys matching their names do not occur in the emit-map. The emit functions must return seqables (e.g. vectors) of method definitions in the format expected by reify: in this way, the case with multiple method definitions returned for one "magic method specifier" is relatively simple. If the iface argument were replaced with ifaces and ~iface with ~#ifaces in reify-from-maps' body, multiple interfaces could be specified for implementation.
Here's another approach, possibly easier to reason about:
(defn compile-atom-bean-converter [ifaces get-set-map]
(eval
(let [asym (gensym)]
`(fn [~asym]
(reify ~#ifaces
~#(apply concat
(for [[k [g s]] get-set-map]
[`(~g [~'this] (~k #~asym))
`(~s [~'this ~'v]
(swap! ~asym assoc ~k ~'v))])))))))
This calls on the compiler at runtime, which is somewhat expensive, but only needs to be done once per set of interfaces to be implemented. The result is a function which takes an atom as an argument and reifies a wrapper around the atom implementing the given interfaces with getters and setters as specified in the get-set-map argument. (Written this way, this is less flexible than the previous approach, but most of the code above could be reused here.)
Here's a sample interface and a getter/setter map:
(definterface IFunky
(getFoo [])
(^void setFoo [v])
(getFunkyBar [])
(^void setWeirdBar [v]))
(def gsm
'{:foo [getFoo setFoo]
:bar [getFunkyBar setWeirdBar]})
And some REPL interactions:
user> (def data {:foo 1 :bar 2})
#'user/data
user> (def atom-bean-converter (compile-atom-bean-converter '[IFunky] gsm))
#'user/atom-bean-converter
user> (def atom-bean (atom-bean-converter data))
#'user/atom-bean
user> (.setFoo data-bean 3)
nil
user> (.getFoo atom-bean)
3
user> (.getFunkyBar data-bean)
2
user> (.setWeirdBar data-bean 5)
nil
user> (.getFunkyBar data-bean)
5
The point is reify being a macro itself which is expanded before your own set-and-get macro - so the set-and-get approach doesn't work. So, instead of an inner macro inside reify, you need a macro on the "outside" that generates the reify, too.
Since the trick is to expand the body before reify sees it, a more general solution could be something along these lines:
(defmacro reify+ [& body]
`(reify ~#(map macroexpand-1 body)))
You can also try to force your macro to expand first:
(ns qqq (:use clojure.walk))
(defmacro expand-first [the-set & code] `(do ~#(prewalk #(if (and (list? %) (contains? the-set (first %))) (macroexpand-all %) %) code)))
(defmacro setter [setterf kw] `(~setterf [~'this ~'v] (swap! ~'data assoc ~kw ~'v)))
(defmacro getter [getterf kw] `(~getterf [~'this] (~kw #~'data)))
(expand-first #{setter getter}
(reify HugeInterface
(getter getX :x)
(setter setX :x)))