Comparison of Text templating vs Compiler Extensibility
In this post, I would like to wrap up a quick tour of compiler extensibility with a few thoughts on how it compares to Text Templates.
Text Templates
It is easy to get started with text templates and the tools. In most cases, you probably have a file that looks similar to what you want to generate that you can edit slightly to make a template file.
It is also very flexible as to what type of files it can generate. It is also very easy to visualize what you will get since the template should be pretty similar to the generated output.
Because the template engine allows you to mix C# in your template, it is very easy to handle conditional generation and generating output within a loop.
Once you have your template ready, you do need to know how to integrate the tool into your build system. You can edit your templates in a simple text editor, but it would be nice if there was more tool support for it. Visual Studio doesn’t seem to currently have syntax highlighting to help match the open/close tags or a way to configure the tool to pass arguments to the template engine from the UI.
Once you get going, it takes a lot of time fiddling with the templates to get the white space the way you want it.
The Text template engine does provide helpful diagnostics when your C# code in the template doesn’t compile or run as expected.
Compiler Extensibility
There is a bigger initial cost to using compiler extensibility for code generation. You need to understand the compiler, the extensibility possibilities, and have a rough idea of how the syntax of the language will affect what you can do. There is also time needed to understand the AST structures.
Extending the compiler involves a mix of code and simple templates used to create and manipulate the AST. The quasi quotation mechanism is apparently not quite as flexible as the template system. The result of this is that it is not always clear what code structure you will get from your compiler extension.
Once you get familiar with compiler extensibility, though, there are things you can do more easily than with text templates. One is to combine output from multiple extensions in the same class, including merging code in constructors. The second is that you have access to the entire AST, not just the part you are generating.
Summary
For most people, it is much easier to get started with text templates since you probably already have a file similar to what you want your output to be. It is just a matter of integrating the code generation into your build system. You can accomplish quite a bit with text templates and clever factoring of your code using partial classes. If you are really doing advanced things, then compiler extensibility may be the way to go.
If you have worked with code generation and have some different way of doing it, or have some helpful tips to share. Please leave a comment.
Series