Hygienic Macro
Subject: Computer and Technology noun /haɪˈdʒiː.nɪk ˈmæk.roʊ/ 1 definition
- programming-languages
- compiler-design
- metaprogramming
- lexical-scoping
-
Definition (noun)
Entry #272 · UpdatedA Hygienic Macro is a syntactic macro whose compile-time expansion preserves lexical scoping and prevents accidental identifier capture between a macro's definition and its call site. During expansion, the macro expander tracks scope metadata or renames generated bindings so that variables introduced by the macro cannot shadow caller variables, while free identifiers inside the macro continue to resolve in its defining environment. Unlike textual preprocessor macros or unhygienic Lisp-style macros—which risk subtle name collisions unless authors manually generate fresh symbols with
gensym—hygienic macros make syntactic abstraction safe and composable by default. While strict hygiene blocks implicit injection of new bindings into the caller's scope, many systems provide explicit escape primitives when intentional capture, such as anaphoric binding, is required.Common Forms
Pattern-Based Declarative Macros: Match input code against structural templates or token-tree rules and enforce hygiene on generated bindings without imperative expansion logic, as exemplified by Scheme's
syntax-rulesand Rust'smacro_rules!.Procedural Syntax-Object Macros: Execute arbitrary compile-time code over syntax objects that carry lexical scope metadata—such as marks or scope sets—to perform complex transformations while preserving hygiene, as used in Scheme's
syntax-caseand Racket.Syntactic Closure Macros: Wrap template expressions with explicit environment objects so generated identifiers bind in the macro's definition scope while caller arguments evaluate in the invocation scope, as implemented in MIT Scheme and Dylan.
Module-Scoped AST Macros: Transform parsed abstract syntax trees using automatic variable renaming (
gensym) and module-qualified symbol resolution, while offering explicit opt-out constructs like Julia'sescor Elixir'svar!for deliberate capture.
Example
In Scheme, a
swap!macro built withdefine-syntaxandsyntax-rulesbinds an internal temporary variabletmp, yet calling(swap! tmp count)whentmpholds10andcountholds25still exchanges them to25and10. Because the expander assigns distinct lexical scope marks to macro-generated bindings and resolves free identifiers likeset!in the macro's defining environment, the expansion avoids both variable capture and accidental shadowing at the call site.