Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 36 ยท Macros and Protocols

Writing Better Macros

Write safe Clojure macros: avoid variable capture with gensym and auto-gensyms, evaluate arguments once, build binding forms, and know when to prefer functions.

The basics lesson showed how to write a macro with defmacro, syntax quote and unquote. This lesson is about writing macros that are correct. Most macro bugs come from three things: names that collide with the caller's names, arguments evaluated more than once, and macros that are really functions in disguise.

Variable capture and hygiene

Suppose we write a macro that evaluates an expression twice and returns the larger time-like result, using a local result:

CLOJURE
(defmacro bad-twice [expr]
  `(let [result ~expr]
     [result result]))

Syntax quote helps immediately: result inside a syntax-quoted form becomes user/result, which is not a legal local binding name, so let throws "Can't let qualified name". The language is stopping you from capturing. Now try to work around it with a quote:

CLOJURE
(defmacro worse-twice [expr]
  (list 'let ['result expr] ['result 'result]))

(let [result 5]
  (worse-twice (* result 2)))

Here the caller's result should be 5, so the expected answer is [10 10]. The macro expands into (let [result (* result 2)] [result result]), which still works by luck, but change the macro to bind result before evaluating a second piece of user code and the user's result silently refers to the macro's variable instead. This is variable capture: macro-introduced names shadow the caller's names. Hygienic code makes that impossible.

Auto-gensym: name#

Inside a syntax-quoted form, a symbol ending in # is replaced by a fresh, unique symbol (all occurrences within the same syntax quote get the same one):

CLOJURE
(defmacro twice [expr]
  `(let [result# ~expr]
     [result# result#]))

(macroexpand-1 '(twice (+ 1 2)))
;=> (clojure.core/let [result__1234__auto__ (+ 1 2)] [result__1234__auto__ result__1234__auto__])

The number in the generated name varies. The point: result__1234__auto__ cannot clash with anything the caller wrote.

gensym

When a generated name must be shared across separate syntax-quote forms (or across a let in the macro body itself), call gensym explicitly:

CLOJURE
(defmacro with-timing [& body]
  (let [start (gensym "start")]
    `(let [~start (System/nanoTime)
           result# (do ~@body)]
       (println "elapsed ms:" (/ (- (System/nanoTime) ~start) 1e6))
       result#)))

start here is an ordinary Clojure variable inside the macro (it holds a symbol), and ~start inserts that symbol into the generated code.

Evaluate arguments once

If a macro uses an argument several times, the argument expression runs several times, with its side effects repeated:

CLOJURE
(defmacro bad-square [x] `(* ~x ~x))
(bad-square (do (println "evaluating") 3))
;; prints "evaluating" TWICE

(defmacro square [x] `(let [v# ~x] (* v# v#)))
(square (do (println "evaluating") 3))
;; prints once, returns 9

The pattern is: bind each argument to a gensym'd local first, then use the local.

Deliberate capture: anaphoric macros

Occasionally you want to introduce a name the user can see, such as it. Doing this on purpose is called an anaphoric macro, and in Clojure you must opt out of qualification with ~'it:

CLOJURE
(defmacro if-let-it [expr then else]
  `(let [~'it ~expr]
     (if ~'it ~then ~else)))

(if-let-it (first []) (str "found " it) "nothing")   ;=> "nothing"

~'it means "unquote a quoted symbol": the plain, unqualified it. Use sparingly and document it; the standard library's -> and as-> solve the same problem in a more explicit way (as-> lets the user name the binding).

Macros that define things

Macros that create definitions or bindings should look like the built-ins. Conventions:

  • Names for definition macros start with def (defroute); for body-taking macros with- (with-timing).
  • The body is & body, spliced with ~@body into a do or let.
  • Binding macros take a vector, like let: (with-resource [r (open)] ...). Destructure the vector in the macro.
CLOJURE
(defmacro with-resource [[sym init] & body]
  `(let [~sym ~init]
     (try
       ~@body
       (finally (.close ~sym)))))

This is nearly how with-open is defined. Notice ~sym: the name comes from the caller, so it is intentionally visible.

A macro that defines functions can generate a family of them with do:

CLOJURE
(defmacro defgetters [& names]
  `(do ~@(for [n names]
           `(defn ~(symbol (str "get-" n)) [m#] (get m# ~(keyword n))))))

(defgetters name age)
(get-name {:name "Ana"})   ;=> "Ana"

Note the nested syntax quote inside for; the outer one has ~@ to splice the list of generated defn forms.

Prefer functions, keep macros thin

A well-behaved macro mostly rewrites syntax and calls a function for the real work:

CLOJURE
(defn run-timed [label f]
  (let [t (System/nanoTime), r (f)]
    (println label (/ (- (System/nanoTime) t) 1e6) "ms")
    r))

(defmacro timed [label & body]
  `(run-timed ~label (fn [] ~@body)))

Now run-timed can be tested, passed around and used with map, and the macro is a one-liner of syntactic sugar. This is the single most useful habit for macro authors.

Debugging checklist

  1. macroexpand-1 the call and read the result.
  2. Look for names without # that collide, and arguments used twice.
  3. Check ~ vs ~@: a body inserted with ~ instead of ~@ produces a call to the first form.
  4. Remember macros run at compile time: you cannot use a runtime value as macro input, only the code you wrote.
  5. A macro cannot be passed as a value: (map my-macro xs) fails. Wrap it in (fn [x] (my-macro x)) if the arguments are known at the call site, or write a function.

Try it: hygiene, in JavaScript

The stand-in below shows variable capture and the gensym fix. Code is built as JavaScript source strings (our "macro expansion"), then run with new Function.

JS Capture versus gensym

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try it: evaluate once

This example counts how many times an argument expression runs under a "macro" that pastes the expression twice, versus one that binds it first.

JS Double evaluation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does result# do inside a syntax-quoted form?

    Auto-gensym creates a fresh name such as result__1234__auto__, used consistently within that syntax quote.
  2. 2. What is wrong with (defmacro bad-square [x] `(* ~x ~x))?

    Each ~x pastes the expression, so side effects run twice. Bind it to a local first.
  3. 3. What does ~'it do?

    Unquoting a quoted symbol avoids namespace qualification, which is how anaphoric macros introduce a visible name.
  4. 4. What is the recommended style for the real work of a macro?

    A thin macro that delegates to a function is easier to test, compose and debug.

Summary

  • Syntax quote qualifies symbols; name# and gensym create fresh names to avoid capture.
  • Evaluate each argument once by binding it to a gensym'd local.
  • ~'sym introduces a visible name on purpose; use rarely.
  • Binding and definition macros follow let/with-open/def conventions; splice bodies with ~@.
  • Keep macros thin, delegate to functions, and always inspect with macroexpand-1.

Next: Protocols and Records