Search code examples
clojuremacroslispclojurescriptleiningen

Why is my clojurescript macro not working


I need when-not-empty-let macro similar to clojure/core's when-let. So, I've just added not-empty call to when-let macro from clojure's source code:

(defmacro when-not-empty-let
  "bindings => binding-form test
  When test is not empty, evaluates body with binding-form bound to the value of test"
  [bindings & body]
  (.log js/console "check")
  (let [form (first bindings) tst (second bindings)]
    `(let [temp# ~tst]
       (when (not-empty temp#)
         (let [~form temp#]
           ~@body)))))

(also replaced (bindings 0) with (first bindings) as it didn't compile otherwise)

I use it in a following way:

(defn something
  []
  (when-not-empty-let [foo ["foo"]]
    (.log js/console foo)))

(something)

I'm getting following output:

undefined

check

What am I doing wrong?


Builded with Clojure v1.9.0, ClojureScript: v1.10.126, lein-cljsbuild: v1.1.7

Tested in Chrome v59.0.3071.115 under Ubuntu.


UPD: jsbin that reproduces issue (at least for me): https://jsbin.com/liluwer/1/edit?js,output

See output from question in browser's developer tool console.


Solution

  • From ClojureScript docs:

    There is a strict rule for when you can use defmacro -- you can only use it in what we call a macro namespace, effectively forcing you to separate your compile time and runtime code.

    The error is I tried to test the macro in the same namespace.