Friday, November 8, 2002

Code Generation

John Lam writes about code generation as a means of capturing abstractions:

During my code generation experiments, I was able to condense approximately 8000 lines of hand-written C# code into about 600 lines of a custom XML language that was in turn fed to about 500 lines of scripting code that generated a functionally equivalent parser. While I was writing this software, I was continuously amazed by the subtle semantics that kept popping up while I was defining my custom XML language. This led to an iterative development process where I would see a new abstraction, modify my language, tweak my code generator, and then test the results of the change using traditional tools (in my case Visual Studio .NET).

Paul Graham has written a lot about how Lisp’s excellent support for code generation (macros) is its most distinguishing feature:

I wonder if these patterns are not sometimes evidence of case (c), the human compiler, at work. When I see patterns in my programs, I consider it a sign of trouble. The shape of a program should reflect only the problem it needs to solve. Any other regularity in the code is a sign, to me at least, that I’m using abstractions that aren’t powerful enough—often that I’m generating by hand the expansions of some macro that I need to write. (Beating the Averages)
The source code of the Viaweb editor was probably about 20-25% macros. Macros are harder to write than ordinary Lisp functions, and it’s considered to be bad style to use them when they’re not necessary. So every macro in that code is there because it has to be. What that means is that at least 20-25% of the code in this program is doing things that you can’t easily do in any other language. (Revenge of the Nerds)

Comments RSS · Twitter

Leave a Comment