Lookery Dev Blog RSS

"Stream of geeky consciousness..." @electromute


Authors
@ckelly@danmil
@dcancel@eliast

Friends


Archive

Nov
3rd
Mon
permalink

Erlang Metaprogramming

Hey, guess what?  If you know what you’re doing, you can rewrite the parse tree of an Erlang file at compile time (!).  You add the following line to your file (or, say, in some header):

-compile(parse_transform, Module).

And Module is handed a parse tree, which it can then rewrite as it desires, and which is then passed on to the rest of the compiler.

It’s not defmacro, but it gives you some very, very interesting opportunities.  For example, I’m about 95% certain this is how the Mnesia db implements Query List Comprehensions, which are list comprehensions which are automagically turned into Mnesia SELECT-type statements.  Almost like you can roll your own LINQ, which is sexy as hell (I’ve wanted to do that in Python, but there’s no way that doesn’t involve some very, very hairy manipulation of bytecode and/or the stack).

Philip Robinson walks one through how to do this sort of thing at:

http://chlorophil.blogspot.com/2007/04/erlang-macro-processor-v2-part-i.html

Oh, and I should finally add that this is probably not something to undertake lightly.  The man page for erl_id_trans, a sample just-plan-identity transform that comes with OTP, has the following priceless line:

Note: Programmers are strongly advised not to engage in parse transformations and no support is offered for problems encountered

-Dan M

Comments (View)
blog comments powered by Disqus