Hygienic macro

Hygienic macro

Hygienic macros are macros whose expansion is guaranteed not to cause collisions with existing symbol definitions. They are a feature of programming languages such as Scheme and Dylan.

Contents

The hygiene problem

In a programming language that has unhygienic macros, it is possible for existing variable bindings to be hidden from a macro by variable bindings that are created during its expansion. In C, this problem can be illustrated by the following fragment:

#define INCI(i) {int a=0; ++i;}
int main(void)
{
    int a = 0, b = 0;
    INCI(a);
    INCI(b);
    printf("a is now %d, b is now %d\n", a, b);
    return 0;
}

Running the above through the C preprocessor produces:

int main(void)
{
    int a = 0, b = 0;
    {int a=0; ++a;};
    {int a=0; ++b;};
    printf("a is now %d, b is now %d\n", a, b);
    return 0;
}

So the variable a declared in the top scope is never altered by the execution of the program, as the output of the compiled program shows:

a is now 0, b is now 1

Note that some C compilers, such as gcc, have an option like -Wshadow that warns when a local variable shadows a global variable, which would have caught the above problem. The simplest and least robust solution is to give the macro's variables unique names:

#define INCI(i) {int INCIa=0; ++i;}
int main(void)
{
    int a = 0, b = 0;
    INCI(a);
    INCI(b);
    printf("a is now %d, b is now %d\n", a, b);
    return 0;
}

Until a variable named INCIa is created, this solution produces the correct output:

a is now 1, b is now 1

The "hygiene problem" can extend beyond variable bindings. Consider this Common Lisp macro:

(defmacro my-unless (condition &body body)
 `(if (not ,condition)
    (progn
      ,@body)))

While there are no references to variables in this macro, it assumes the symbols "if", "not", and "progn" are all bound to their usual function definitions. If, however the above macro is used in the following code:

(flet ((not (x) x))
  (my-unless t
    (format t "This should not be printed!")))

Because the definition of "not" has been locally altered, the message "This should not be printed!" will be printed, which is probably not the intended behavior. The problem can be fixed by manually inserting the desired function object into the return value of the macro.

(defmacro my-unless (condition &body body)
 `(if (funcall ',#'not ,condition)
    (progn
      ,@body)))

however, this approach can be problematic for code marshaling done by some compilers, and it is not possible to "protect" macro uses this way. (E.g., the "funcall" and the "progn" in the above can be broken too, with no way of protecting them.)

Strategies

In some languages such as Common Lisp, Scheme and others of the Lisp language family, macros provide a powerful means of extending the language. Here the lack of hygiene in conventional macros is resolved by several strategies.

  • Obfuscation. If the programmer needs to use temporary storage during the expansion of a macro, he can use one with an unusual name and hope that the same name will never be used in a program that uses his macro. Of course any programmer knowing of gensym won't do this. (See next point)
  • Temporary symbol creation. In some programming languages it is possible for a new variable name, or symbol, to be generated and bound to a temporary location. The language processing system ensures that this never clashes with another name or location in the execution environment. The responsibility for choosing to use this feature within the body of a macro definition is left to the programmer. This method was used in MacLisp, where a function named "gensym" could be used to generate a new symbol name. Similar functions (usually named gensym as well) exist in many Lisp-like languages, including the widely implemented Common Lisp[1] standard.
  • Hygienic transformation. The processor responsible for transforming the patterns of the input form into an output form detects symbol clashes and resolves them by temporarily changing the names of symbols. This kind of processing is supported by Scheme's "let-syntax" and "define-syntax" macro creation systems. The basic strategy is to identify bindings in the macro definition and replace those names with gensyms, and to identify free variables in the macro definition and make sure those names are looked up in the scope of the macro definition instead of the scope where the macro was used.

Hygienic macro systems for Scheme

Syntax-rules

Syntax-rules is the standard high-level macro system of R5RS.

(define-syntax swap!
  (syntax-rules ()
    ((_ a b)
     (let ((temp a))
       (set! a b)
       (set! b temp)))))

Syntax-case

Syntax-case is a low- and high-level macro system that is part of R6RS.

(define-syntax swap!
  (lambda (stx)
    (syntax-case stx ()
      ((_ a b)
       (syntax
        (let ((temp a))
          (set! a b)
          (set! b temp)))))))

Syntactic closures

Syntactic closures are another type of macro system.

(define-syntax swap!
   (sc-macro-transformer
    (lambda (form environment)
      (let ((a (close-syntax (cadr form) environment))
            (b (close-syntax (caddr form) environment)))
        `(let ((temp ,a))
           (set! ,a ,b)
           (set! ,b temp))))))

Explicit renaming

Explicit renaming is another type of macro system.

(define-syntax swap!
 (er-macro-transformer
  (lambda (form rename compare)
    (let ((a (cadr form))
          (b (caddr form))
          (temp (rename 'temp)))
      `(,(rename 'let) ((,temp ,a))
           (,(rename 'set!) ,a ,b)
           (,(rename 'set!) ,b ,temp))))))

References


See also


Wikimedia Foundation. 2010.

Игры ⚽ Нужно решить контрольную?

Look at other dictionaries:

  • Syntactic closure — In computer science, syntactic closures are an implementation strategy for a hygienic macro system. The actual arguments to a macro call are closed in the current environment, such that they cannot inadvertently reference bindings introduced by… …   Wikipedia

  • MLisp — is also another name for Mocklisp, a stripped down version of Lisp used as an extension language in Gosling Emacs. MLISP is a variant of Lisp with an Algol like syntax based on M Expressions, which were the function syntax in the original… …   Wikipedia

  • SISC — Infobox Software name = SISC logo = caption = Second Interpreter of Scheme Code developer = Scott G. Miller latest release version = 1.16.6 latest release date = February 27, 2007 operating system = Cross platform via JVM genre = Programming… …   Wikipedia

  • Scheme — Семантика: функциональный Тип исполнения: интерп …   Википедия

  • Common Lisp — Paradigm(s) Multi paradigm: procedural, functional, object oriented, meta, reflective, generic Appeared in 1984, 1994 for ANSI Common Lisp Developer ANSI X3J13 committee Typing discipline …   Wikipedia

  • Racket (programming language) — Racket Paradigm(s) Multi paradigm: Functional, Procedural, Modular, Object oriented, Reflective, Meta Appeared in 1994 Developer …   Wikipedia

  • Evaluation strategy — Evaluation strategies Strict evaluation Applicative order Call by value Call by reference Call by sharing Call by copy restore Non strict evaluation Normal order Call by name Call by need/Lazy evaluation …   Wikipedia

  • Metaprogramming — This article is about the computer programming technique. For the management technique, see Metaprogramming (management). Programming paradigms Agent oriented Automata based Component based …   Wikipedia

  • PLT Scheme — Infobox Software name = PLT Scheme caption = developer = PLT latest release version = 4.1 latest release date = Release date and age|2008|08|12 latest preview version = latest preview date = operating system = Cross platform platform = x86, PPC,… …   Wikipedia

  • Extensible programming — is a term used in computer science to describe a style of computer programming that focuses on mechanisms to extend the programming language, compiler and runtime environment. Extensible programming languages, supporting this style of programming …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”