Syntactic Abstraction: The syntax-case expander
R. Kent Dybvig · 2007
When writing computer programs, certain patterns arise over and over again. For example, programs must often loop through the elements of arrays, increment or decrement the values of variables, and perform multi-way conditionals based on numeric or character values. Programming language designers typically acknowledge this fact by including special-purpose syntactic constructs that handle the most common patterns. C, for instance, provides multiple looping constructs, multiple conditional constructs, and multiple constructs for incrementing or otherwise updating the value of a variable [9]. Some patterns are less common but can occur frequently in a certain class of programs or perhaps just within a single program. These patterns might not even be anticipated by a language’s designers, who in any case would typically choose not to incorporate syntactic constructs to handle such patterns in the language core. Yet, recognizing that such patterns do arise and that specialpurpose syntactic constructs can make programs both simpler and easier to read, language designers sometimes include a mechanism for syntactic abstraction, such as C’s preprocessor macros or Common Lisp [11] macros. When such facilities are not present or are inadequate for a specific purpose, an external tool, like the m4 [8] macro expander, might be brought to bear. Syntactic abstraction facilities differ in several significant ways. C’s preprocessor macros are essentially token-based, allowing the replacement of a macro call with a sequence of tokens with text from the macro call substituted for the macro’s formal parameters, if any. Lisp macros are expression-based, allowing the replacement of a single expression with another expression, computed in Lisp itself and based on the subforms of the macro call, if any. In both cases, identifiers appearing within a macro-call subform are scoped where they appear in the output, rather than where they appear in the input, possibly leading to unintended capture of a variable reference by a variable binding. For example, consider the simple transformation of Scheme’s or form [7] into let and if below. (Readers unfamiliar with Scheme might want to read ∗ This document appeared as a chapter of Beautiful Code: Leading Programmers Explain How They Think, edited by Andy Oram and Greg Wilson and published by O’Reilly and