All entries for Friday 04 August 2006
August 04, 2006
.NET 2.0 has some very cool stuff in System.Reflection.Emit, namely the DynamicMethod class. DynamicMethod will let you create a new method at runtime that lives inside your current assembly. The only hitch is that you have to create the method using IL – not a high level language like C#/VB/Boo/etc.
My thought for today is: Can we use the syntactic macro abilities of .NET languages like Boo and Nemerle to create dynamic method code whilst remaining in the source language.
For example (psuedo–Nemerle):
myMethod = dynamic( Console.WriteLine("Hello, World") );
myMethod() // Call the dynamically generated method
At compile time this would take the AST passed to the "dynamic" macro, call out to the Nemerle compiler and retrieve the IL. This IL is then used to create a sequence of Emit*() calls needed to create the dynamic method. Finally the macro creates a delegate that can be used to call the method.
Whilst that may seem rather complex, once working it totally removes the need to drop to IL to generate dynamic methods at runtime. I've not had time to think through the implementation details of this. For now I'm just throwing the idea out there – If someone wants have a go, please feel free! The main sticking point is really working out an escaping system to allow interpolation of real code and IL emits. This can probably be done using a second macro "normal" that switches back to normal code.
There is something rather magic about using compile–time macros to generate code for runtime methods. It feels like both sides of meta–programming sync up so nicely, adding a whole new dimension to "code that writes code"! :)