Categories
patterns

Pattern Patter: Templates/Macros

Summary: You want to extend a language without writing a new compiler.
 

Forces

  • Working in a particular language.
  • Want to extend it for convenience.
  • Subroutines are not a convenient mechanism: either they’re unavailable or don’t fit syntactically.

Example

C is extended with a macro language. Pro*C (Oracle) extends C with Oracle features.

Resolution

Use a source-to-source translation via a macro or template language.

Discussion

Macro facilities are often syntactically orthogonal to the rest of the language. For example, in C you can do this:

#define STARTCALL(a) f(a

You have to worry about compile-time vs run-time. The macro language can execute at compile-time. For example, Bliss (a low-level systems language similar to C) has an elaborate macro tool that can populate tables via arbitrary functions.
The “modern” approach is to avoid a macro language. Java has none; C++ has a number of mechanisms that reduce the need for macros.

More uses

  • Macro assemblers
  • M4/Awk/Perl etc.

[Written 12-1-98]