Thursday, August 17, 2006

Smerl Attains Erlang Metaprogramming Nirvana (or maybe not)

Update (8/17): Today may not have been my lucky day after all. Apparently, erlang:fun_info doesn't behave identically in the shell and in a compiled module. I'm trying to figure out a way around this but this may be a big roadblock. We may even have to forget about those nice fun expressions and go back to abstract forms :(



...



What does erlang:fun_info do? erlang:fun_info returns a list of tuples that contain metadata about a fun expression -- including the fun expression's abstract form representation.



What did I use it for? To enhance Smerl so that Smerl users never have to to write source fragments or know a single thing about Erlang abstract forms!



Here's the new approach to Erlang (runtime) metaprogramming:




A = 17,
C1 = smerl:new(foo),
{ok, C2} = smerl:add_func(C1, bar,
fun(B, C) -> D = 5, A + B + C + D end),
ok = smerl:compile(C2),
foo:bar(3, 7). %% returns 17 + 3 + 7 + 5 = 32


The astute reader would notice that Smerl supports closures. How? Smerl gets information about closure variables from erlang:fun_info, and expands them in the beginning of the new function. Cool, huh? :)



Another great benefit to this approach is that the compiler now verifies the syntactic correctness of your runtime-compiled code. Indeed, this capability blurs the line between compile-time and run-time Erlang metaprogramming.



I can't wait to see what Erlang developers are going to do with this. I have some ideas in mind but I can't say I know all the possibilities Smerl opens. If you have some thoughts, please share :) Also, please try this out and let me know if you have any problems.



Note: smerl:replace_func now supports fun expressions as well.

No comments: