2011

A code generator you can debug: recursion instead of a pipeline

At one job I wrote a command processor, essentially a code generator in C++. In went descriptions of commands; out came source code.

The old version was built as a pipeline. First all the commands are parsed into one data structure. Then processing: they pick up new information, which is the second data type. Then a third type: how they will be written to the file. And all of this went in layers side by side: first every command through the first stage, then every command through the second, then through the third.

Trouble started when an error turned up in the output file, a syntax error or something else. Debugging it was simply impossible: there was no telling where that data had come from. We had to set memory breakpoints with conditions like “if this is such-and-such a command with such-and-such numbers” and watch what got into it and where.

When we made the new version, I was given a free hand from the start, and I did it differently: recursively. Take the first command and carry it almost to the output code straight away. You can’t write the whole source at once: in C++ a single command has both a declaration in the header and an implementation. So I made several output channels: the header goes into one, the implementation into another, and so on. I think there were up to four channels.

And it worked brilliantly. If a syntax error appeared in the output, you set a breakpoint where that piece is written, and the call stack shows everything: which command it came from, where in the configs it was defined, what affected what.

Before, this generator had been rewritten from scratch roughly every two years, for each new format. In my version new things and new schemes simply plugged in, with no rewrite. That is why this architecture is still in use, some fifteen years later.

What I took from it: a pipeline of layers is nice to draw, but it loses the link between output and input. If you carry one unit of data through all the stages at once, the call stack itself becomes the history of where everything came from.