En kodare


Anders Hovmöller
GitHub twitter email

Code generation is terrible and great

2017-08-03

Are you generating code for the language you are writing in? Then the language you’re using is terrible. By definition it’s under powered because you need to write code to write code instead of just expressing what you need directly.

That said there is a place for writing custom code generators. Right now I’m writing a code generator for Elm based on Ned Batchelder’s tool Cog. The primary reason I wanted to do this is because Elm is an under powered language. Some of that is a very deliberate feature (the total lack of side effects), others are a consequence of the language being young and yet others are because the core team doesn’t yet care about some problems enough to prioritize it and/or there’s no known good solution.

I would have preferred Elm being more expressive, but when I started thinking about my situation I realized there are some interesting positive side effects to writing a code generator for Elm. But first things first:

How is Elm under powered?

The basic problem is that we as users of Elm don’t have access to the same information as the compiler:

Why Elm?

So you might conclude that I think Elm is not a very good language since it requires code generation and you’d be right. But I’m still arguing for Elm over ClojureScript at work partly because of the limitations of Elm. It’s a much smaller language and much stricter so you can know that a lot of guarantees hold in all the Elm code. This is not the case in ClojureScript, for better and for worse. Another thing about Elm is that what it does, it does extremely well. It can do that with such a small team behind it because it is insanely focused. I want to take advantage of that.

I’m arguing that if we go with Elm we must have a good code generation system in place from day one. I’m betting on Cog for three reasons:

Introducing elm-cog

I want to start a discussion about code generation tooling for Elm and I’m doing it by creating a tool and open sourcing it. I think having open source tools would help in many ways:

Goals of elm-cog

Features so far

Example

Here’s an example of a generated enum. First you write this:

--- [[[cog enum('Baz', 'D, E, F') ]]]  
--- [[[end]]]

Then after you’ve run elm-cog on your source code you’ll get:

-- [[[cog enum('Baz', 'D, E, F') ]]]  
  
  
type Baz  
   = D  
   | E  
   | F  
  
  
baz_list =  
   [ D, E, F ]  
  
  
  
-- [[[end]]]

Never be afraid your list and your enum are out of sync again!

Join me!

Come to github and help! Feature requests, bugs, pull requests, stories of pain points you’ve had in Elm that might be solved by elm-cog, it’s all welcome!

« OCaml — first impressions Overanalyzing kids shows: Bing »