Metaprogramming: Erlang macros from ground up

Murphees Rant - Werner Schuster - April 26, 2007

So you want to know how a macro system is built from the ground up? No, not the bad kind of macro… I mean a LISPish type of macro. Philip Robinson has a great series explaining how he built different macro implementations in Erlang.
There‘s the series title Erlang Macro Processor (v1)   and it’s sequel Erlang Macro Processor (v2) where he reworks his project.

His Atomiser is a great example of a DSL, or at least just fancy metaprogramming in action. Basically, he implements a kind of enumerated type (enum).  Atomes (similar to Ruby’s Symbols) are very useful, but sometimes it’d be nice to be able to group a set of atoms. One old example is the enum type for weekdays, which you could define as [monday, tuesday, wednesday, thursday, friday, saturday, sunday]. If you have a function set_weekday, it’d be nice if the compiler warned you if you called with with set_weekday(knoedelday). Philip makes this possible with nothing but a bit of magic pixie dust called parse_transform which allows you to tranform Erlang ASTs. Since this code runs at compile time, Atomiser allows to give you warnings about unknown type literals at … well, compile time, just as enum type implementations in other languages too.

I won‘t go into the implementation (it‘s well enough explained anyway), but it‘s really neat and, again, shows how flexible languages can be extended without having to picket outside the language maintainers offices or ripping open the language specification.

If your interest has been sparked, the Joe Armstrong (the guy behind Erlang) is writing an Erlang book for the Pragmatic Programmers: Programming Erlang: Software for a Concurrent World

Oh… and for those of you, who stay away from cocktail parties because you worry a conversation might veer into the topic of LISP Macros and you‘re not up to snuff with that: Practical Common Lisp  Seriously, the best book on LISP and it features an incredibly compelling introduction to LISP macros. If you ever wondered what the fuzz about internal DSLs is about, this is the book to read.



Categories: Blogs  Murphees Rant