Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 38 ยท Macros

defmacro and Backquote Templates

Write Common Lisp macros with defmacro, backquote, comma and comma-at, use &body and &key lambda lists, and see how templates replace manual list building.

Last lesson showed that a macro returns a list. Building that list with list and quote works but quickly becomes unreadable. Lisp's answer is the backquote template: write the shape of the code you want, and mark the holes with commas.

Common Lisp snippets are read-only (no Lisp runtime on this site). The JavaScript examples are labelled stand-ins that model how templates are filled in.

defmacro

defmacro looks like defun, but its parameters receive unevaluated forms and its body must return a form:

LISP
(defmacro my-when (test &body body)
  (list 'if test (cons 'progn body)))

(my-when (> x 0)
  (print "positive")
  (incf count))

The call expands to (if (> x 0) (progn (print "positive") (incf count))). &body is a synonym of &rest that tells editors to indent the rest of the form as a body.

Backquote, comma and comma-at

A backquote (`) starts a template. Inside it everything is quoted except what you mark:

Syntax Meaning
`(a b c) the list (a b c), like '(a b c)
,expr evaluate expr and insert the value
,@expr evaluate expr (a list) and splice its elements in

The same macro with a template:

LISP
(defmacro my-when (test &body body)
  `(if ,test (progn ,@body)))

Here ,test inserts the test form and ,@body splices the body forms into progn. Without the @, you would get (progn ((print "positive") (incf count))), which tries to call (print "positive") as a function. Forgetting @ for &body is the most common first bug.

LISP
(let ((xs '(1 2 3)))
  `(a ,xs b))     ; => (A (1 2 3) B)
(let ((xs '(1 2 3)))
  `(a ,@xs b))    ; => (A 1 2 3 B)
JS Stand-in: filling a template

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

No output.

Lambda lists for macros

Macro lambda lists are more powerful than function ones. You can destructure:

LISP
(defmacro my-let1 ((var value) &body body)
  `(let ((,var ,value))
     ,@body))

(my-let1 (x 10)
  (* x x))      ; => 100

The first parameter (var value) takes the list apart in place, so the call reads naturally. You can also use &key, &optional and &aux, even nested:

LISP
(defmacro repeat (n &body body)
  `(dotimes (,(gensym) ,n) ,@body))   ; see the gensym lesson for why this is incomplete

(defmacro with-timing ((&key (label "block")) &body body)
  `(let ((start (get-internal-real-time)))
     (multiple-value-prog1 (progn ,@body)
       (format t "~a: ~d ticks~%" ,label (- (get-internal-real-time) start)))))

The with-timing macro hides a variable-capture hazard (start). The gensym lesson fixes it.

Computing at expansion time

Because the macro body is ordinary Lisp, you can compute while expanding. A comma can hold any expression:

LISP
(defmacro unroll-add (n)
  `(+ ,@(loop repeat n collect 1)))

(unroll-add 3)   ; expands to (+ 1 1 1)

Another common technique builds a family of definitions:

LISP
(defmacro define-getters (class &rest slots)
  `(progn
     ,@(loop for s in slots
             collect `(defun ,(intern (format nil "~a-~a" class s)) (obj)
                        (slot-value obj ',s)))))

Note the nested backquote template inside collect, and ',s, which inserts the symbol quoted so the generated code refers to the slot name rather than evaluating it as a variable.

JS Stand-in: generating several definitions

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

No output.

Nested backquotes and a warning

Backquotes can nest (macro-defining macros), and each level needs its own comma. That is advanced; most macros never need it. A simpler warning applies to ordinary code: a macro must return code, never run the effect itself. Compare:

LISP
(defmacro bad-log (msg)
  (format t "LOG: ~a~%" msg)   ; runs at expansion time, once, during compilation
  nil)

(defmacro good-log (msg)
  `(format t "LOG: ~a~%" ,msg))   ; runs every time the generated code runs

bad-log prints while the file is compiled and does nothing at run time.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does ,@xs do inside a backquote template?

    ,@ is comma-at: the value must be a list and its elements are inserted in place.
  2. 2. Given (let ((xs '(1 2))) (a ,xs))`, what is the result?

    A plain comma inserts the value as ONE element, so the list (1 2) is nested.
  3. 3. Why use &body instead of &rest in a macro lambda list?

    &body is a synonym for &rest; its purpose is indentation and readability.
  4. 4. What is wrong with a macro that calls (format t ...) directly in its body instead of in the returned template?

    Code in the macro body runs while expanding; only the returned form runs at run time.

Summary

  • defmacro defines a compile-time function from forms to a form.
  • Backquote writes the code shape; ,x inserts a value and ,@x splices a list.
  • Macro lambda lists support destructuring, &body, &key and &optional.
  • Anything computed in the macro body happens at expansion time; the template is what runs later.
  • Forgetting @ before a body is the classic bug.

Next: macroexpand and Debugging Macros