common-lisp MACROEXPAND


Example

Macro expansion is the process of turning macros into actual code. This usually happens as part of the compilation process. The compiler will expand all macro forms before actually compiling code. Macro expansion also happens during interpretation of Lisp code.

One can call MACROEXPAND manually to see what a macro form expands to.

CL-USER> (macroexpand '(with-open-file (file "foo")
                        (do-something-with file)))
(LET ((FILE (OPEN "foo")) (#:G725 T))
  (UNWIND-PROTECT
      (MULTIPLE-VALUE-PROG1 (PROGN (DO-SOMETHING-WITH FILE)) (SETQ #:G725 NIL))
    (WHEN FILE (CLOSE FILE :ABORT #:G725))))

MACROEXPAND-1 is the same, but only expands once. This s useful when trying to make sense of a macro form that expands to another macro form.

CL-USER> (macroexpand-1 '(with-open-file (file "foo")
                          (do-something-with file)))
(WITH-OPEN-STREAM (FILE (OPEN "foo")) (DO-SOMETHING-WITH FILE))

Note that neither MACROEXPAND nor MACROEXPAND-1 expand the Lisp code on all levels. They only expand the top-level macro form. To macroexpand a form fully on all levels, one needs a code walker to do so. This facility is not provided in the Common Lisp standard.