Generic Programming Using Cee Macros

Many interpreters and compilers are written in the CeeLanguage, instead of specialized grammars like EBNF.

C requires considerable code redundancy. This redundancy can be reduced by using macros and other CeePreprocessorStatements.

 /* This example comes up often in interpreters */
 #define Func(name, OP) name(int a, int b) { return a OP b; }

/* we can call the macros with very simple code */ Func(add, +) Func(sub, -)

/* It will expand to code like: */ /* add(int a, int b) { return a + b); } sub(int a, int b) { return a - b); } */

This is a CodeGeneration technique. Brian Kernighan wrote a paper about an awk to C translator he wrote(http://cm.bell-labs.com/cm/cs/who/bwk/awkc++.ps). At one point he said "The thought of adding another type and another 75 functions to manage it was more than I could bear." This is the phenomenon that I'm claiming this macro approach solves (actually it turns out to be MetaMacros and CodeGeneration, but I'll skip that for the moment). Using the approach I am advocating, he wouldn't have to manage another 75 functions, it would happen automatically.

One way to avoid using macros like this is to switch to a different language. Interpreters and compilers can be written using special grammars. One can express a grammar cleanly using a syntax specifically designed for that purpose, rather than define a new syntax via C macros. EBNF (Extended BackusNaurForm) and the ANTLR (AntlrTranslatorGenerator) meta-language are well documented. The grammars and Java code are pretty and easy to understand. Lots of folks know them.


CeePreprocessorStatements, ExtensibleProgrammingLanguage

EditText of this page (last edited November 17, 2008) or FindPage with title or text search