Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 38 ยท Macros and Languages

Hygiene and syntax-case

Understand hygienic macros and variable capture, then move to syntax-case, with-syntax and syntax-parse in Racket, with a runnable JavaScript capture demo and renaming stand-in.

Macros that paste code together can accidentally change what names mean. Imagine a my-or macro that stores the first value in a temporary variable called t. If the user's own code also has a variable named t, a naive macro would confuse them. Scheme and Racket macros are hygienic: the expander keeps the macro's names and the user's names separate automatically, so these collisions cannot happen.

This lesson explains the problem, shows how hygiene solves it, and then introduces syntax-case and Racket's syntax-parse, the more powerful tools you use when pattern/template rules are not enough. It builds on Syntax-rules Macros.

The Racket macro code is read-only because our site cannot run an expander. The JavaScript blocks are stand-ins that demonstrate the capture problem with string-based expansion and a renaming fix.

The capture problem

Here is my-or written as the plain text rewriting a C preprocessor would do:

Text
my-or(a, b)  =>  (let ([t a]) (if t t b))

and a user who writes:

RACKET
(let ([t 5])
  (my-or #f t))

After naive expansion you would get (let ([t 5]) (let ([t #f]) (if t t t))). The user's t (5) is hidden by the macro's t, so the answer is #f, not 5. This bug is called variable capture. In languages with textual macros it is a constant source of subtle failures.

The stand-in below does exactly that kind of expansion with strings, so you can see the bug:

JS Stand-in: naive text macros capture variables

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

No output.

The first result is false instead of 5: the macro's t shadowed the user's. The second renames the macro's temporary to a fresh name, so the user's t is untouched.

What hygiene guarantees

A hygienic expander does the renaming for you. It guarantees two things:

  • Names the macro introduces (like tmp) cannot capture or be captured by names in the user's code.
  • Free names in the macro template (like if or list) refer to what they meant where the macro was defined, even if the user has shadowed them at the use site.

So with define-syntax-rule you can write the obvious version of my-or, and it just works:

RACKET
(define-syntax-rule (my-or a b)
  (let ([t a]) (if t t b)))

(let ([t 5]) (my-or #f t)) ; => 5

Sometimes you want to break hygiene on purpose, for example an anaphoric aif that binds it for the user. In Racket you do that with explicit tools such as datum->syntax or syntax parameters (make-parameter-like forms at compile time), so it is a deliberate act and not an accident.

syntax-case and with-syntax

syntax-rules can only rearrange the pieces it matches. When you need to compute something at expansion time, such as generating a name, counting arguments or checking a condition, use syntax-case. It matches like syntax-rules, but the right-hand side is ordinary Racket code that returns a syntax object built with syntax (written #'):

RACKET
(require (for-syntax racket/base))

(define-syntax (check-positive stx)
  (syntax-case stx ()
    [(_ n)
     (if (and (number? (syntax-e #'n)) (<= (syntax-e #'n) 0))
         (raise-syntax-error 'check-positive "expected a positive number" #'n)
         #'n)]))

(check-positive 5)   ; => 5
;; (check-positive -2) is rejected while compiling, before the program runs

Here the macro examines n at compile time and rejects bad input before the program runs, with an error that highlights the exact source. syntax-e unwraps a syntax object to its datum. with-syntax binds new pattern variables, which is how you build lists of generated identifiers.

syntax-parse: friendly macros

Racket's syntax-parse (from syntax/parse) adds syntax classes such as id, expr, number and str to the pattern, giving automatic type checks and good error messages:

RACKET
(require (for-syntax racket/base syntax/parse))

(define-syntax (define-getter stx)
  (syntax-parse stx
    [(_ name:id field:id)
     #'(define (name obj) (hash-ref obj 'field))]))

(define-getter get-age age)
(get-age (hash 'age 42 'name "Ada")) ; => 42
;; (define-getter 5 age) fails with: expected identifier

Compare that to a bare syntax-rules, where (define-getter 5 age) would expand into confusing code and fail somewhere else. For libraries, syntax-parse is the standard choice.

Phases: why for-syntax?

Macro code runs at compile time, a separate phase from the program's run time. Names available at run time are not automatically available at compile time, so you write (require (for-syntax racket/base)) to import the language into the compile-time phase. This separation is also why Racket can compile a module to run without its macros: they were consumed during compilation.

flowchart LR
  S["Source with macros"] --> E["Expander (phase 1: macro code runs)"]
  E --> C["Core forms"]
  C --> R["Run time (phase 0)"]

Macro functions live in phase 1; the code they generate runs in phase 0.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is variable capture?

    With textual expansion, a macro's temporary variable can clash with a user variable of the same name, silently changing the meaning of the program.
  2. 2. What does a hygienic expander guarantee?

    The expander tracks where each identifier came from and renames internally so there are no accidental collisions.
  3. 3. When would you choose syntax-case or syntax-parse over syntax-rules?

    They allow arbitrary compile-time code and checks, which pure pattern/template rules cannot express.
  4. 4. Why (require (for-syntax racket/base))?

    Macro transformers run at compile time (phase 1), where run-time imports are not available automatically.

Summary

  • Naive textual macros suffer from variable capture; Scheme/Racket macros are hygienic and avoid it.
  • Hygiene keeps macro-introduced names and user names separate, and free names keep their definition-site meaning.
  • syntax-case runs real code at expansion time; syntax-parse adds syntax classes and better error messages.
  • Macro code lives in a separate compile-time phase, imported with for-syntax.

Next: Languages with #lang