Linking a .NET Expression Tree into a new assembly

允我心安 提交于 2019-12-05 01:28:09

问题


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?


回答1:


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

lambdaExpression.CompileToMethod(myMethodBuilder);



回答2:


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)



来源:https://stackoverflow.com/questions/1618682/linking-a-net-expression-tree-into-a-new-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!