Converting Delegates to Expression Trees 22 Apr 2009


Plage du diamant Back when I was working at db4o, we had fun implementing a mechanism somehow similar to LINQ, to have strongly typed queries expressed using code itself. The implementation uses Mono.Cecil and Cecil.FlowAnalysis to decompile a delegate into an AST, that db4o's query optimizer can process. Since .net 3.5, an API, System.Linq.Expressions, can be used to get a representation of a C# lambda expression into an object graph. An expression tree. .net 4.0 will add support for statements to this API, but as far as I know, the language itself hasn't been updated to produce those new nodes. Anyway, a few days ago, someone on Stack Overflow, asked how to turn a delegate into a LINQ expression tree. There's no builtin feature to do that, it's not a straightforward process. You basically have to decompile the compiled method. I guess it's a good thing that I'm working on a decompiler, if I need to decompile something. Tonight I wrote a short spike to verify the feasibility of my idea, and it turns out to be pretty simple. Sample:
static void Main ()
{
	Func magic = i => i * 42;

	Expression> expression =
		DelegateConverter.ToExpression (magic);

	Console.WriteLine (expression.ToString ());
	// prints: i => i * 42
	Console.WriteLine (expression.Compile ().Invoke (1));
	// prints: 42
}
DelegateConverter is implemented as a simple visitor which walks over a Cecil.Decompiler AST, and generates, if possible, the according Linq Expression Tree. Pretty cool isn't it? You can browse the code of the spike. Keep in mind that it's nowhere to be complete, and that it's just a proof of concept. Still, I think it's a pretty cool usage of the Cecil.Decompiler library.