Code generation with Cog

Tuesday 10 February 2004

Cog is a code generation tool I wrote to solve some problems at work. It's based on embedding Python in source files to generate code (we use it to generate C++, for example).

I'm really happy with the way Cog turned out. Some would say that Cog isn't a code generation tool at all, but just a file munger that can be used for code generation. They would be right, Cog does much less than most "code generators". But it was written to munge files in just the way you need to when generating code. Cog only does one thing, and it does it well: it executes chunks of Python it finds in text files, capturing the output and writing it into the file alongside the original code.

Download it, try it out, and let me know what you think.

For more about code generation in general, try:

  • Dave Thomas interviewed about code generation. Dave Thomas is one of the Pragmatic Programmers, and I find I agree with him almost universally. He forbids putting the output of code generators under source control, I encourage it. We agree that the output should never be edited.
  • The Code Generation page on the c2 wiki. As will happen with a wiki, this fractures off in many directions, with many different viewpoints, both for and against code generation.


Jack Herrington 1:20 PM on 11 Feb 2004

You should check out the cgn-talk Yahoo Group. There we talk about code generators and what is going on in the CG world. You may be able to get some folks interested in using your generator.

Ville Vainio 9:44 AM on 17 Feb 2004

This seems pretty much like what I use empy for:

Dave Fuller 9:45 AM on 17 Feb 2004

Dave Thomas is right about not having generated code checked into source control. The mechanism to create the code and the data and meta-data from which the code is created does, however, need to be under source control. Otherwise, it is too tempting for somebody to edit the source.

Add a comment:

Ignore this:
not displayed and no spam.
Leave this empty:
not searched.
Name and either email or www are required.
Don't put anything here:
Leave this empty:
URLs auto-link and some tags are allowed: <a><b><i><p><br><pre>.