gogen
Code generation template language
What
A template language that has a template per type and works similar to the visitor pattern. Each node that needs to be rendered does that by rendering its own template defined by its type.
Example
main visitor:
pkg.AST type:
Title ${.Title}
{for c, item in .Items}
${c}: @{item}
{end}
pkg.Item type:
${.Label} (${.Count})
Syntax documentation
Syntax documentation
Why
So far when I had to generate some code I used two aproaches:
Template language
With template languages like jinja, handlebars or whatever you can easily generate code from an AST or a similar composite datastructure.
Although it works pretty well for simpler generators it ends up in a mess when the generated code is getting more complex and a lot of logic needs to be either in the AST or template language.
Another problem is reusability. Although most template languages support macros or at least includes it's usually unintuitive and makes the code look clutered.
Visitor pattern
The second aproach is to let a visitor traverse the AST and output code for each node. Usually i have different visitors to generate different representations of the same node.
This works very well for complex code but is not well suited for bigger chunks of simple code and also quite a bit of boilerplate is needed.
GoGen approach
Trying to eliminate the shortcomings i combined the two approaches. Instead of creating one template that iterates trough the whole AST a small template is created for each node.
So when a node is visited, it's template is executed and the result is inserted.