Scheme advanced macros
last modified November 24, 2026 Guile 3.0
The syntax-rules macros rewrite code by
patterns and templates alone. syntax-case keeps the patterns but
lets an ordinary Scheme procedure, the transformer, build the
result. The transformer can test its input, compute values while the program
is being expanded, report syntax errors, and create new identifiers, which is
also how hygiene can be broken on purpose. This article covers
syntax-case and its helpers, syntax parameters, and Guile's
older define-macro, with GNU Guile 3.0.7.
From syntax-rules to syntax-case
A macro defined with syntax-case is a procedure of one argument,
a syntax object that holds the macro use together with the
information needed for hygiene. syntax-case matches it against
patterns, and (syntax template), written
#'template for short, builds the result.
(define-syntax swap!
(lambda (stx)
(syntax-case stx ()
((_ a b)
#'(let ((tmp a))
(set! a b)
(set! b tmp))))))
(define first 1)
(define second 2)
(swap! first second)
(write (list first second))
(newline)
(define-syntax my-unless
(lambda (stx)
(syntax-case stx ()
((_ test body ...)
(syntax (if test #f (begin body ...)))))))
(my-unless (< first second)
(display "first is not less than second")
(newline))
swap! and my-unless are the macros from the
syntax-rules article written in the longer form. The transformer receives
the whole use as stx, and each clause pairs a pattern with an
expression that returns the new code. Pattern variables can only be used
inside #' or syntax, as in the template of
my-unless. For macros like these, syntax-rules is
shorter; syntax-case pays off when the transformer needs to
compute something.
$ guile syntaxcase.scm (2 1) first is not less than second
Fenders
A clause of syntax-case may have a fender, an
expression between the pattern and the result. The clause is chosen only when
the pattern matches and the fender returns true. syntax->datum
strips a syntax object down to a plain list, symbol, or number, and
datum->syntax turns plain data back into code.
(define-syntax inc!
(lambda (stx)
(syntax-case stx ()
((_ var)
(identifier? #'var)
#'(set! var (+ var 1)))
((_ var n)
(identifier? #'var)
#'(set! var (+ var n))))))
(define-syntax square
(lambda (stx)
(syntax-case stx ()
((_ x)
(number? (syntax->datum #'x))
(let ((n (syntax->datum #'x)))
(datum->syntax stx (* n n))))
((_ x)
#'(let ((v x)) (* v v))))))
(define counter 0)
(inc! counter)
(inc! counter 4)
(write counter)
(newline)
(write (square 12))
(newline)
(write (square (+ counter 1)))
(newline)
identifier? checks that the argument of inc! is a
variable name, so only names can be incremented. square has two
clauses. When its argument is a number literal, the fender of the first
clause is true, and the transformer computes the square at expansion time
and returns the number 144 as the code. Any other argument falls through to
the second clause, which builds an ordinary multiplication.
datum->syntax takes the macro use as its first argument: the
new code gets the same lexical context.
$ guile fenders.scm 5 144 36
Reporting syntax errors
When no clause matches, Guile reports that the source expression failed to
match any pattern. syntax-violation gives a better message: it
takes the name of the macro, a message, the whole form, and optionally the
subform at fault.
(define-syntax inc!
(lambda (stx)
(syntax-case stx ()
((_ var)
(identifier? #'var)
#'(set! var (+ var 1)))
((_ other)
(syntax-violation 'inc! "expected a variable" stx #'other)))))
(define visits 0)
(inc! visits)
(display visits)
(newline)
(inc! 5)
The second clause of inc! catches every argument that is not a
variable and reports it. The error is found while the file is compiled, so
compilation fails and Guile prints the message as a warning. It then runs the
file in the interpreter, which expands one top-level form at a time: the first
inc! still runs and prints 1 before the bad form stops the
program. The backtrace is omitted from the output.
$ guile violation.scm ;;; WARNING: compilation of violation.scm failed: ;;; Syntax error: ;;; violation.scm:14:6: inc!: expected a variable in subform 5 of (inc! 5) 1 ice-9/psyntax.scm:2795:12: In procedure syntax-violation: Syntax error: violation.scm:14:0: inc!: expected a variable in subform 5 of (inc! 5)
Computing at expansion time
The transformer is a full Scheme procedure, so it can loop, use lists, and
call built-in procedures. with-syntax binds new pattern
variables to computed code, which can then be used in a template, including
with the ellipsis.
(define-syntax power
(lambda (stx)
(syntax-case stx ()
((_ base n)
(exact-integer? (syntax->datum #'n))
(with-syntax (((factor ...)
(make-list (syntax->datum #'n) #'b)))
#'(let ((b base))
(* factor ...)))))))
(define-syntax fib-table
(lambda (stx)
(syntax-case stx ()
((_ n)
(let loop ((k (syntax->datum #'n)) (a 0) (b 1) (acc '()))
(if (= k 0)
(datum->syntax stx `(quote ,(reverse acc)))
(loop (- k 1) b (+ a b) (cons a acc))))))))
(define x 3)
(write (power x 4))
(newline)
(write (power (+ x 1) 3))
(newline)
(write (power 2 0))
(newline)
(write (fib-table 15))
(newline)
power unrolls an integer power. The fender requires a literal
exponent; make-list makes a list of n copies of the
identifier b, and with-syntax binds it to
factor ..., so (power x 4) becomes
(let ((b x)) (* b b b b)). The base is evaluated only once.
For exponent 0, (*) returns 1. fib-table computes
the first Fibonacci numbers in a named let during expansion and
returns the list as a quoted constant built with
quasiquote; the program itself only prints
it.
$ guile compiletime.scm 81 64 1 (0 1 1 2 3 5 8 13 21 34 55 89 144 233 377)
Helpers and expansion time
Macros are expanded while a file is compiled, before any of its definitions have run. A transformer can therefore call built-in procedures, but not a procedure defined in the same file in the usual way.
(define (celsius->fahrenheit c)
(+ 32 (* 9/5 c)))
(define-syntax fahrenheit
(lambda (stx)
(syntax-case stx ()
((_ c)
(datum->syntax stx (celsius->fahrenheit (syntax->datum #'c)))))))
(display "boiling: ")
(display (fahrenheit 100))
(newline)
The transformer of fahrenheit calls
celsius->fahrenheit, which does not exist yet when the
compiler expands the macro. Compilation fails with an unbound variable. Guile
then falls back to the interpreter, which runs the definition before it
expands the macro use, so the program still prints the right answer. Each run
repeats the failed compilation, and the program runs more slowly without the
compiled code.
$ guile helper.scm ;;; WARNING: compilation of helper.scm failed: ;;; Unbound variable: celsius->fahrenheit boiling: 212
eval-when
eval-when controls when the definitions inside it are evaluated.
With expand they exist while the macros of the file are
expanded, and with load and eval they also exist
when the compiled or interpreted program runs.
(eval-when (expand load eval)
(define (celsius->fahrenheit c)
(+ 32 (* 9/5 c))))
(define-syntax fahrenheit
(lambda (stx)
(syntax-case stx ()
((_ c)
(number? (syntax->datum #'c))
(datum->syntax stx (celsius->fahrenheit (syntax->datum #'c))))
((_ c)
#'(celsius->fahrenheit c)))))
(display "boiling: ")
(display (fahrenheit 100))
(newline)
(define room 21)
(display "room: ")
(display (exact->inexact (fahrenheit room)))
(newline)
The helper procedure is now available at both times, and the file compiles
without a warning. fahrenheit converts a literal at expansion
time and leaves a call to the helper for any other expression, so
(fahrenheit room) is converted when the program runs. The
exact result 349/5 is shown as an inexact number. The usual alternative to
eval-when is to put the helpers in a separate
module.
$ guile evalwhen.scm boiling: 212 room: 69.8
Generating identifiers
Identifiers built by datum->syntax take the lexical context
of the syntax object given as the first argument. When that is a name from
the macro use, the new identifier is visible to the code around the macro,
which allows a macro to define new names.
(define-syntax define-enum
(lambda (stx)
(define (make-name prefix item)
(datum->syntax prefix
(symbol-append (syntax->datum prefix)
'-
(syntax->datum item))))
(syntax-case stx ()
((_ type item ...)
(with-syntax (((name ...)
(map (lambda (i) (make-name #'type i))
#'(item ...)))
((index ...)
(iota (length #'(item ...))))
(all (make-name #'type #'all)))
#'(begin
(define name index) ...
(define all '(item ...))))))))
(define-enum color red green blue)
(define-enum size small large)
(write (list color-red color-green color-blue))
(newline)
(write color-all)
(newline)
(write (list size-small size-large size-all))
(newline)
(write (list-ref color-all color-blue))
(newline)
define-enum defines a constant for each item, named after the
type and the item. The local procedure make-name joins the
symbols with symbol-append and gives the result the context of
the type name. with-syntax binds three pattern variables at
once: the generated names, their indexes from iota, and the name
of a list of all items. #'(item ...) is a list of syntax
objects, so map and length work on it. The macro
expands to a begin with several definitions, which is allowed at
top level.
$ guile identifiers.scm (0 1 2) (red green blue) (0 1 (small large)) blue
Breaking hygiene
Hygiene normally keeps a variable introduced by a macro invisible to the code
it wraps. Sometimes this is exactly what a macro should break. An
anaphoric macro binds a fixed name, such as it, that
the user's code refers to.
(define-syntax aif
(lambda (stx)
(syntax-case stx ()
((_ test then else)
(with-syntax ((it (datum->syntax stx 'it)))
#'(let ((it test))
(if it then else)))))))
(define stock '((apples . 12) (pears . 0) (plums . 7)))
(define (report fruit)
(aif (assq fruit stock)
(begin
(display fruit)
(display ": ")
(display (cdr it)))
(begin
(display fruit)
(display ": unknown")))
(newline))
(report 'plums)
(report 'kiwis)
(write (aif (memv 3 (list 1 2 3 4)) (length it) 0))
(newline)
aif is an if that binds the value of the test to
it. Created with datum->syntax in the context of
the macro use, the identifier it belongs to the user's code, so
the branches can refer to it. With a plain #'it in the
template, the name would be renamed by the expander and the branches would
report an unbound variable. assq and memv return
useful true values, which suits this macro well.
$ guile anaphoric.scm plums: 7 kiwis: unknown 2
Identifier macros
identifier-syntax creates a macro that is used as a plain name
instead of in parentheses. Every reference to the name is replaced by the
template, and a second clause can define what set! on the name
does.
(define stack (list 1 2 3)) (define-syntax top (identifier-syntax (car stack))) (write top) (newline) (set! stack (cons 0 stack)) (write top) (newline) (define-syntax size (identifier-syntax (_ (length stack)) ((set! _ n) (set! stack (list-tail stack (- (length stack) n)))))) (write size) (newline) (set! size 2) (write stack) (newline) (write (+ top size)) (newline)
top looks like a variable but is replaced by
(car stack) wherever it appears, so it always shows the current
top of the stack. size has two clauses: the first handles a
reference, and the second turns (set! size 2) into code that
keeps only the last two elements. Identifier macros are useful for aliases,
but they hide computation behind a name, so they are used sparingly.
$ guile identmacro.scm 1 0 4 (2 3) 4
Syntax parameters
A syntax parameter is a keyword with a default meaning that a
macro can change within the code it wraps. It gives anaphoric macros without
giving up hygiene: it is a real binding that can be imported,
renamed, and shadowed like any other.
(define-syntax-parameter it
(lambda (stx)
(syntax-violation 'it "it used outside of aif" stx)))
(define-syntax aif
(syntax-rules ()
((_ test then else)
(let ((value test))
(syntax-parameterize ((it (identifier-syntax value)))
(if value then else))))))
(define stock '((apples . 12) (pears . 0) (plums . 7)))
(define (amount fruit)
(aif (assq fruit stock) (cdr it) 0))
(write (map amount '(apples plums kiwis)))
(newline)
(write (aif (assq 'pears stock)
(aif (zero? (cdr it)) 'sold-out 'available)
'unknown))
(newline)
define-syntax-parameter defines it with a
transformer that reports an error, so it outside of
aif is a syntax error. Inside aif,
syntax-parameterize rebinds it to an identifier macro for the
hidden variable value. Because the macro is again written with
syntax-rules, nesting works naturally: in the inner
aif, the test (zero? (cdr it)) uses the outer
it, and the branches would see the inner one.
$ guile parameters.scm (12 7 0) sold-out
define-macro
Guile also supports define-macro, the traditional Lisp macro. It
is a procedure that receives the arguments of the macro use as plain lists and
symbols and returns a list, usually built with quasiquote. It is simple, but
it is not hygienic.
(define-macro (swap-unsafe! a b)
`(let ((tmp ,a))
(set! ,a ,b)
(set! ,b tmp)))
(define-macro (swap-safe! a b)
(let ((tmp (gensym "tmp")))
`(let ((,tmp ,a))
(set! ,a ,b)
(set! ,b ,tmp))))
(define x 1)
(define y 2)
(swap-unsafe! x y)
(write (list x y))
(newline)
(let ((tmp 1) (other 2))
(swap-unsafe! tmp other)
(write (list tmp other))
(newline))
(let ((tmp 1) (other 2))
(swap-safe! tmp other)
(write (list tmp other))
(newline))
swap-unsafe! works for x and y, but
when one of the variables is called tmp, the expansion is
(let ((tmp tmp)) (set! tmp other) (set! other tmp)), and the
values are not swapped. swap-safe! avoids the clash by naming its
temporary variable with gensym, a symbol that
cannot appear in the user's code. Free names in the template, such as
let and set!, can still be captured by local
bindings, so new code should use syntax-rules or
syntax-case.
$ guile definemacro.scm (2 1) (1 2) (2 1)
Source
Syntax-case — GNU Guile Reference Manual
Syntax Parameters — GNU Guile Reference Manual
Lisp-style Macro Definitions — GNU Guile Reference Manual
In this article we have written transformers with syntax-case,
selected clauses with fenders, reported errors with
syntax-violation, computed code at expansion time with
with-syntax and datum->syntax, made helpers
available with eval-when, generated new identifiers, broken
hygiene on purpose, written identifier macros and syntax parameters, and
compared them with Guile's define-macro. The
macros with syntax-rules article covers the
basics, and the pattern matching
article uses a similar pattern language on data at run time.
Author
List all Scheme tutorials.