Lisp - Compiler Macros



A Macro in LISP, is a powerful tool to transform code, to generate code. A compiler macro is similar to general macro with a difference that a compiler macro is to be invoked by Compiler during its optimization phase. In this chapter, we're discussing both macro and compiler macro to compare them and their usage.

Purpose

  • LISP Macro is for syntactic extension. Using LISP macro, we can define new constructs which can expand into existing LISP Code. A LISP Macro transforms a s-expression into other s-expressions.

  • Compiler Macro on the other hand, is a way to optimize code during compilation phase. Using compiler macro, we can define transformation for a particular function which compiler can apply to replace them with more efficient code.

Timing of Applying a Macro

  • LISP Macro is expanded before compilation phase. When LISP Compiler encounters a LISP Macro, it is expanded to underlying code. So we can generate code at compile time.

  • Compiler Macro is invoked by LISP Compilier in optimization phase. Using compiler macros, we've fine-grained control over how compiler to generate more efficient machine code.

Defining a Macro

  • LISP Macro is defined using defmacro. A LISP Macro arguments are unevaluated. During compilation phase, LISP macro code is expanded to underlying code.

  • Compiler Macro is defined using define-compiler-macro. A compiler macro is associated with particular function. When compiler encounters that function call, compiler macro is invoked. A compiler macro is used to give compiler an information on how to compile certain functions.

Key Differences

So main difference between a normal macro and compiler macro is that normal macro is to transform the code before compiler is to compile it whereas compiler macro transform the code while compiler is processing code.

A normal macro is for syntactic extension and code generation whereas compiler macro is for compiler optimization and code transformation at low level.

Advertisements