Question

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?

Was it helpful?

Solution

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

lambdaExpression.CompileToMethod(myMethodBuilder);

OTHER TIPS

In order to emit raw IL you need to define your own AST. You need to Get AssemblyBuilder then ModuleBuilder and then you can define module-level method or get new TypeBuilder and now MethodBuilder to define class-level method.

You said that you already have lexer and parser. that means you able to build AST. So just walk through the parsed expressions and emit your IL.

Even if you get generated(by Compile) code you'll not be able to do something useful with it since generated code depends on infrastructure. For example if you need to compile closures then you should create class or other store fo lexical variables and so on(like non lexical control transfer which require to use Exceptions in .net)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top