Skip to main content
Definition Website Computer and Technology

Hygienic Macro

Subject: Computer and Technology noun /haɪˈdʒiː.nɪk ˈmæk.roʊ/ 1 definition

  1. Definition (noun)

    Entry #272 · Updated

    A 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-rules and Rust's macro_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-case and 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's esc or Elixir's var! for deliberate capture.

    Example

    In Scheme, a swap! macro built with define-syntax and syntax-rules binds an internal temporary variable tmp, yet calling (swap! tmp count) when tmp holds 10 and count holds 25 still exchanges them to 25 and 10. Because the expander assigns distinct lexical scope marks to macro-generated bindings and resolves free identifiers like set! in the macro's defining environment, the expansion avoids both variable capture and accidental shadowing at the call site.