Search code examples
.netexpression-treescilreflection.emit

Linking a .NET Expression Tree into a new assembly


I'm trying to write my own toy My Toy Language -> MSIL compiler in order to get a better understanding of how compilers work. I got the parsing and lexing working, I have built the expression trees and using the System.Linq.Expressions expression tree API, I have a working interpreter. Now I would like to emit some real MSIL assemblies.

The problem is, I can't figure out how to actually build these assemblies. The MethodBuilder class only accepts raw MSIL method bodies, so I have to get the raw MSIL of my expression tree. Calling Expression.Compile() returns a working delegate but I'm not able to get its underlying MSIL. Calling MethodInfo.GetMethodBody() throws an InvalidOperationException since it's not implemented in that specific child class.

How can I link that delegate into a new assembly?


Solution

  • Just found it. The DLR version of LambdaExpression exposes a CompileToMethod method which does exactly what I need.

    lambdaExpression.CompileToMethod(myMethodBuilder);